1

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.

4
  • 2
    clone is the fastest method and it may make a real difference for larger lists. You can make an unchecked cast into the needed generic type. Commented Nov 7, 2013 at 13:56
  • 1
    Do note, however, that clone makes 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. Commented Nov 7, 2013 at 13:57
  • @MarkoTopolnik I am only supposed to write this function for generic type and hence cannot use unchecked casting. Commented Nov 7, 2013 at 14:00
  • There's nothing stopping you from using unchecked casts and in the case of clone, it's 100% safe. Basically, it's just a work around the ineptitude of the Java Generics model. Commented Nov 7, 2013 at 14:01

1 Answer 1

2

To copy a list, you have to create a new list and fill it with items from the old list.

The constructor you are using might not actually be the best option, though. If you check the source code (google arraylist source code) you notice that it creates an array that is exactly as big as there are elements in the old collection.

Then it adds an element to that array. Because the array is too small, it has to create another copy of the array, only a bit bigger, and move the elements there again.

You could get a better performance by using

clone = new ArrayList(queue.size() + 1);
clone.addAll(queue);
clone.add(e);

Also, method names should start with a lower case letter. So use: enqueueModified(...)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.