标签:
//直接上代码:
public static void main(String[] args) { List<Integer> list = new Vector<Integer>(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<Integer> reList = new Vector<Integer>(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<Integer> intset = new HashSet<Integer>(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<Integer> notReList = new Vector<Integer>(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);
}
版权所有,转载请注明出处:http://www.cnblogs.com/langtianya/p/4676816.html
找出现有Vector或ArrayList或数组中重复的元素&给现有Vector或ArrayList或数组去重
标签:
原文地址:http://www.cnblogs.com/langtianya/p/4676816.html