您在BeanUtils.getCopy(sourceBean)使用可以做這樣的事情:
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;
不變性意味着將永遠是OK。 newVar
上的操作無法破壞oldVar
,因爲沒有newVar.setValue(newValue)
。
如果你有一個int
直接使用它,並允許Java的自動裝箱把它轉換成一個Integer
:
int oldValue = ... ;
Integer newValue = oldValue ; // Java will automatically put this through
// Integer.valueOf(int i)
你提到你真的想與布爾合作。您應該考慮使用BitSet
。
由於整數是不可變的,你爲什麼要深拷貝它們? –