I have an ArrayList of generic object type, i.e. List queue. I want to write a function EnqueueModified, that takes an arraylist and a list object as input and returns another ArrayList that contains the elments of the old arraylist and the list object but without affecting the original arraylist passed. i.e. Enqueue operation should be performed on a new copy of the arraylist and returned.
This can be done as follows:
public List<E> EnqueueModified(E e, List<E> queue) {
List<E> clone = new ArrayList<E>(queue);
clone.add(e);
return clone;
}
but is there a better method to do this? instead of using a copy constructor, is there any faster way to create a copy of the list? I cannot use cloning as it does not support for generic List.
cloneis the fastest method and it may make a real difference for larger lists. You can make an unchecked cast into the needed generic type.clonemakes a byte-for-byte copy, so if the original happens to be hugely oversized (has a lot of free room left), the clone will be exactly the same in this respect, unlike the instance obtained from the copy constructor.clone, it's 100% safe. Basically, it's just a work around the ineptitude of the Java Generics model.