[英]Adding ArrayList into Another ArrayList
我的程序中有一个ArrayList,我解析一个肥皂对象,每个项目都是一个tempArraylist。在项目迭代完成后,我将此ArrayList添加到另一个Arraylist中,我的问题是它没有添加内容它添加了tempArray的引用。如何添加数组的值而不是它的引用。
这是我的代码。
for (int i = 0; i < count; i++)
{
tempContents.clear();
Log.i(TAG , String.valueOf(count));
Object property = response2.getProperty(i);
if (property instanceof SoapObject)
{
SoapObject category_list = (SoapObject) property;
for(int j = 0 ; j<tags.size() ; j++)
{
if(category_list.getProperty(tags.get(j)).toString().contains("Resim"))
{
String tempResim = "htttp://www.balikesir.bel.tr/";
tempResim += category_list.getProperty(tags.get(j)).toString();
tempContents.add(tempResim);
}
else
{
if(category_list.getProperty(tags.get(j)).toString().equals("anyType{}"))
{continue;}
tempContents.add(category_list.getProperty(tags.get(j)).toString());
}
}
for(int k = 0 ;k < tempContents.size() ; k++ )
Log.i("For ici 5 minare",tempContents.get(k));
Log.i("For disi 4 minare","Asdas asdas");
contents.add(tempContents);
}
}
使用public boolean addAll(Collection<? extends E> c)
contents.addAll(tempContents);
从Java docs
,
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
例
List test = new ArrayList();
test.add("A");
test.add("B");
test.add("C");
test.add("D");
List test1 = new ArrayList();
test1.add("E");
test1.add("F");
test1.add("G");
test1.add("H");
test1.add("I");
//test.add(new ArrayList(test1)); // Dont use this if u want to add content and not entire arrayList as its output will be [A, B, C, D, [E, F, G, H, I]]
test.addAll(test1);
System.out.println(test);
产量
[A, B, C, D, E, F, G, H, I]
重要笔记
1.使用test.add(test1.clone());
仅当test1 reference is of ArrayList type
而不是List类型时,因为List does not implements Cloneable Interface
2.不要使用test.add(new ArrayList(test1));
,如果您想添加内容而不是整个arrayList,则其输出将为[A,B,C,D,[E,F,G,H,I]]。
使用类似这样的东西:
contents.add(new ArrayList(tempContents));
替代方案:
contents.add(tempContents.clone());
选择2:
contents.addAll(tempContents);
选择1或2可将整个ArrayList
作为一项插入,选择3 ArrayList
将所有项作为单独的项添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.