欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java从ArrayList中移除重复项,javaarraylist移除,下面代码演示如何从Arr

来源: javaer 分享于  点击 18735 次 点评:270

java从ArrayList中移除重复项,javaarraylist移除,下面代码演示如何从Arr


下面代码演示如何从ArrayList中移除重复项:

  ArrayList arrayList1 = new ArrayList();  arrayList1.add("A");  arrayList1.add("A");  arrayList1.add("B");  arrayList1.add("B");  arrayList1.add("B");  arrayList1.add("C");  //Create a HashSet which allows no duplicates  HashSet hashSet = new HashSet(arrayList1);  //Assign the HashSet to a new ArrayList  ArrayList arrayList2 = new ArrayList(hashSet) ;  //Ensure correct order, since HashSet doesn't  Collections.sort(arrayList2);  for (Object item : arrayList2)    System.out.println(item);

上述代码移除重复项,并未遍历list而是使用HashSet类,先构造了一个HashSet实例,然后再用hashSet构造了一个ArrayList实例,新实例中已经移除了重复项。

这使用了Set接口中不允许有重复项的特性。上述代码输出:

ABC
相关栏目:

用户点评