Android 两个ArrayList找出相同元素及单个ArrayList删除元素

//从一个ArrayList中删除重复元素

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

 

arrayList1.add("C");

arrayList1.add("A");

arrayList1.add("B");

arrayList1.add("A");

arrayList1.add("B");

arrayList1.add("C");

 

HashSet<String> hashSet = new HashSet<String>(arrayList1);

 

List<String> arrayList2 = new ArrayList<String>(hashSet);

 

for (Object item : arrayList2)

System.out.println(item);

 

//比较两个list中相同的值

//假设比较的List分别为:A,B 建立中间变量C。

首先将A的值克隆给C。使用C.removeAll(B)的方法。这样C中存在的既是A和B中不同的内容。

最后在使用A.removeAll(C)这样最后A中留下的内容即为A,B中相同的内容。

ArrayList<String> arrayList1 = new ArrayList<String>();

 

arrayList1.add("R");

arrayList1.add("A");

arrayList1.add("B");

arrayList1.add("c");

arrayList1.add("B");

arrayList1.add("C");

 

//注意:List并没有clone()方法

ArrayList<String> arrayList2 = new ArrayList<String>();

 

arrayList2.add("W");

arrayList2.add("HR");

arrayList2.add("Y");

arrayList2.add("C");

arrayList2.add("A");

arrayList2.add("B");

 

//如果下一句改为:

ArrayList<String> c = arrayList1;

则后面的arrayList1同c指向同一对象,即,c改变arrayList1也跟着改变。

ArrayList<String> c = (ArrayList<String>) arrayList1.clone();

System.out.println("c " +c);

c.removeAll(arrayList2);

System.out.println("asdjfaawwq" +c);

System.out.println("A "+arrayList1 );

arrayList1.removeAll(c);

System.out.println("array" +arrayList1);

posted @ 2013-09-25 10:04  Pepper.B  阅读(2420)  评论(0编辑  收藏  举报