//直接上代码: public static void main(String[] args) { Listlist = new Vector (20); for (int i = 0; i < 10; i++) { list.add(i % 3); list.add(i % 6); list.add(i % 2); list.add(i % 4); } System.out.println("原始元素:" + list); List reList = new Vector (20); for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i) == list.get(j)) { reList.add(list.remove(i)); i--; break; } } }// System.out.println("去重后:" + list);// System.out.println("重复元素:" + reList);// 输出:// 原始元素:原始元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 4, 0, 0, 2, 5, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 2, 0, 0, 0, 3, 1, 1]// 去重后:[4, 5, 2, 0, 3, 1]// 重复元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 0, 0, 2, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 0, 0, 1] //去重方法2 Set intset = new HashSet (list); System.out.println("set去重后" + intset);// 输出:// 原始元素:[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 0, 2, 0, 3, 1, 3, 1, 4, 0, 0, 2, 5, 1, 1, 0, 0, 0, 2, 1, 1, 1, 3, 2, 2, 0, 0, 0, 3, 1, 1]// set去重后[0, 1, 2, 3, 4, 5] //数组 List notReList = new Vector (20); int[] intarr = new int[]{1, 2, 4, 5, 6, 3, 4, 2, 3, 4, 34, 5, 23, 5, 2, 3, 4, 3, 3,99}; for (int i = 0; i < intarr.length ; i++) { //如果不计算notReList用i < intarr.length改成i < intarr.length-1 if (!notReList.contains(intarr[i])) { notReList.add(intarr[i]); } for (int j = i + 1; j < intarr.length; j++) { if (intarr[i] == intarr[j]) { reList.add(intarr[i]); break; } } } System.out.println("去重后:" + notReList); System.out.println("重复元素:" + reList);// 输出:// 去重后:[1, 2, 4, 5, 6, 3, 34, 23, 99]// 重复元素:[2, 4, 5, 3, 4, 2, 3, 4, 5, 3, 3]
// list和数组也可以互转:// List intList=Arrays.asList(intarr);或// Integer[] intarr2=new Integer[list.size()];// list.toArray(intarr2);
}
版权所有,转载请注明出处: