2016-01-07 38 views
1

有一个在我的项目就像一个自定义对象:复制有限公司项目到另一个列表

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

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

所以,你的说法应该宁可:

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

但是,要小心这些硬编码的指标,因为你可能会得到一个IndexOutOfBoundsException为非法的端点索引值。

0

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

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

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

public boolean add(E e) 

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

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

返回指定fromIndex(包括)元素范围为排他性之间此列表的所述部分的视图。

如果你检查它返回列表的返回类型,所以你需要在c3添加元素的列表而不是单一的元素,所以,按您的使用情况,你应该实现addAll()方法,而不是add()方法。

c3.addAll(c2.subList(0,5)); 
相关问题