DIGITAL JEDI
DIGITAL JEDI

Reputation: 1666

Copy Limited items of ArrayList to another List

There is a custom object in my project like:

  class category{
String id;String item;
.....GET SET METHODS
}

I created the list:

List<category> c2 = new ArrayList<category>();
c2.add(new category(CID, itemName));

Now i want save top five element of c2 to another list c3;

List<category> c3 = new ArrayList<category>();

I tried like this:

c3.add(c2.subList(0,5));

Its a syntax error i know, whats the best method?

Upvotes: 1

Views: 277

Answers (2)

atish shimpi
atish shimpi

Reputation: 5023

Collection framework has following two methods for adding element.

addAll(Collection<? super T> c, T... elements)

Adds all of the specified elements to the specified collection.

public boolean add(E e)

Appends the specified element to the end of this list.

public List<E> subList(int fromIndex,int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

If you check return type of it returning List, so you need to add list of elements rather then single element in c3, So, as per your use case you you should implement addAll() method instead of add() method.

c3.addAll(c2.subList(0,5));

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You almost got it - you should use List#addAll(Collection<? extends E> collection) method instead of the List#add(E element) one, which adds a single element to the List.

So your statement should rather be:

c3.addAll(c2.subList(0, 5));

However, be careful with these hardcoded indices, as you might get a IndexOutOfBoundsException for an illegal endpoint index value.

Upvotes: 2

Related Questions