有个比较器的工具类,这个类好多业务对象需要用到,怎样把这个类写成泛型公用的。
改好了
public class Comparer<T> {
public void compare(List<T> newList, List<T> oldList) {
if (newList != null && !newList.isEmpty()) {
hasNewIds(newList, oldList);
} else {
noHasNewIds(oldList);
}
}
private void hasNewIds(List<T> newList, List<T> oldList) {
//...
}
private void noHasNewIds(List<T> oldList) {
// ...
}
}
public class NewOldComparer<T> {
private List<T> insertIds = new ArrayList<>();
...
}
是值传递。Java 语言的方法调用只支持参数的值传递。当一个对象实例作为一个 参数被传递到方法中时,参数的值就是对该对象的引用。对象的属性可以在被调 用过程中被改变,但对对象引用的改变是不会影响到调用者的。C++和 C#中可以 通过传引用或传输出参数来改变传入的参数的值。在 C#中可以编写如下所示的代 码,但是在 Java 中却做不到。
using System;
namespace CS01 {
class Program {
public static void swap(ref int x, ref int y) {
int temp = x;
x = y;
y = temp;
}
public static void Main (string[] args) {
int a = 5, b = 10;
swap (ref a, ref b); // a = 10, b = 5;
Console.WriteLine ("a = {0}, b = {1}", a, b);
}
}
}
说明:Java 中没有传引用实在是非常的不方便,这一点在 Java 8 中仍然没有得到 改进,正是如此在 Java 编写的代码中才会出现大量的 Wrapper 类(将需要通过 方法调用修改的引用置于一个 Wrapper 类中,再将 Wrapper 对象传入方法), 这样的做法只会让代码变得臃肿,尤其是让从 C 和 C++转型为 Java 程序员的开 发者无法容忍。