You could do something like:
public static List<Integer> clone(List<Integer> source) {
return source.stream()
.map( intObj -> new Integer(intObj.intValue()))
.collect(Collectors.toList());
}
Or, more old-fashioned:
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;
}
Both of these could be made shorter by taking advantage of auto-boxing / auto-unboxing. But I've made it explicit to make it absolutely clear what's going on.
However, it's a pointless exercise - in fact it's actively wasteful of memory and detrimental to performance. Integer
is immutable, so it's better for references to point at the same instance of Integer
. Because it's not possible for the Integer
to change value, it's impossible to cause any harm by sharing an instance.
This holds true for immutable objects in general, and is the reason they are a good thing.
You are very unlikely, as a beginner, to find a case in which new Integer(...)
is a good idea (or even Integer.valueOf(int i)
, although this one might return a cached instance). If you already have an Integer
, use the one you have:
Integer oldVar = ... ;
Integer newVar = oldVar;
Immutability means that will always be OK. It is impossible for an operation on newVar
to corrupt oldVar
because there is no newVar.setValue(newValue)
.
If you have an int
use it directly and allow Java's auto-boxing to convert it into an Integer
:
int oldValue = ... ;
Integer newValue = oldValue ; // Java will automatically put this through
// Integer.valueOf(int i)
You mentioned that you really wanted to work with booleans. You should consider using BitSet
.