文章出處

//直接上代碼:
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 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()