您可以执行以下操作:
public static List<Integer> clone(List<Integer> source) {
return source.stream()
.map( intObj -> new Integer(intObj.intValue()))
.collect(Collectors.toList());
}
或者,更老式的:
public static List<Integer> clone(List<Integer> source) {
List<Integer> newList = new ArrayList<>();
for(Integer intObj : source) {
newList.add(new Integer(intObj.intValue()));
}
return newList;
}
通过利用自动装箱/自动拆箱,可以缩短这两者。但我已经明确表示要绝对清楚发生了什么。
但是,这是一种毫无意义的练习 - 事实上,它会浪费内存并且不利于性能。 Integer 是不可变的,因此更好的引用指向Integer 的同一实例。因为Integer不可能改变值,所以不可能通过共享实例造成任何伤害。
这适用于一般的不可变对象,这也是它们是好东西的原因。
作为初学者,您不太可能找到new Integer(...) 是一个好主意的情况(甚至Integer.valueOf(int i),尽管这可能会返回一个缓存实例)。如果您已经有Integer,请使用您拥有的:
Integer oldVar = ... ;
Integer newVar = oldVar;
不变性意味着永远没问题。对newVar 的操作不可能破坏oldVar,因为没有newVar.setValue(newValue)。
如果您有int,请直接使用它并允许Java 的自动装箱将其转换为Integer:
int oldValue = ... ;
Integer newValue = oldValue ; // Java will automatically put this through
// Integer.valueOf(int i)
您提到您真的很想使用布尔值。您应该考虑使用BitSet。