Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (10.2k points)

I have an ArrayList and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the Collections class which contains a copy method.

Suppose I have the following:

List<String> a = new ArrayList<String>();

a.add("a");

a.add("b");

a.add("c");

List<String> b = new ArrayList<String>(a.size());

Collections.copy(b,a);

This fails because basically it thinks b isn't big enough to hold a. Yes I know b has size 0, but it should be big enough now shouldn't it? If I have to fill b first, then Collections.copy() becomes a completely useless function in my mind. So, except for programming a copy function (which I'm going to do now) is there a proper way to do this?

1 Answer

0 votes
by (46k points)

b has a capacity of 3, but a size of 0. The fact that ArrayList has some sort of buffer capacity is an implementation detail - it's not part of the List interface, so Collections.copy(List, List) doesn't use it. It would be ugly for it to special-case ArrayList.

 using the ArrayList constructor which takes a collection is the way to in the example provided.

For more complicated scenarios (which may well include your real code), you may find the collections within Guava useful.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...