将有限的ArrayList项复制到另一个List

时间:2016-01-07 09:34:21

标签: java arraylist

我的项目中有一个自定义对象,如:

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

我创建了列表:

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

现在我想将c2的前五个元素保存到另一个列表c3;

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

我试过这样:

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

我知道它的语法错误,最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

你几乎得到了 - 你应该使用List#addAll(Collection<? extends E> collection)方法而不是List#add(E element)方法,这会为List添加一个元素。

所以你的陈述应该是:

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

但是,请注意这些硬编码索引,因为您可能会获得非法端点索引值的IndexOutOfBoundsException

答案 1 :(得分:0)

Collection框架有以下两种添加元素的方法。

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

将所有指定的元素添加到指定的集合中。

public boolean add(E e)

将指定的元素追加到此列表的末尾。

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

返回指定fromIndex(包含)和toIndex(独占)之间此列表部分的视图。

如果你检查返回List的返回类型,那么你需要在c3中添加元素列表而不是单个元素,所以,根据你的用例,你应该实现addAll()方法add()方法。

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