I got the unchecked expression error when compiling and found the offending line to be
ArrayList<Integer> items = (ArrayList<Integer>) this.items.clone();
I am trying to perform a deep copy of my object so I am cloning a property of the object and array list in the above manner. How can I fix this warning?
- I could use
@SuppressWarnings("unchecked")but that is just hiding the problem (tho I expect none) - If I clone manually by looping through all elements to it will be slower I think
Whats the correct way of doing this?
If your elements are Integers, performing a “deep copy” really isn’t an issue, since there’s no reason why you would need to copy an Integer object. Just use
new ArrayList<Integer>(this.items).But for reference, neither clone() nor the ArrayList copy constructor will do a deep copy. It’s only because your element types don’t need deep copying that this satisfies your needs.