// 建立有重複項目之 int array
int duplicateArray[] = { 4, 2, 5, 1, 5, 2, 4, 3 };
// 利用 Set 的特性,將所有項目放入 Set 中即可移除重複的項目
Set intSet = new HashSet();
for (int element : duplicateArray) {
intSet.add(element);
System.out.print("=> "+ element);
}
// intSet.size() 為不重複項目的個數
int nonDuplicateArray[] = new int[intSet.size()];
// 將 Set 中的項目取出放到 nonDuplicateArray 中
// 這裡也可以利用 iterator 來達成
Object[] tempArray = intSet.toArray();
for (int i = 0; i < tempArray.length; i++) {
nonDuplicateArray[i] = (Integer) tempArray[i];
}
// 輸出結果:1, 2, 3, 4, 5,
// HashSet 有自己的內部排序機制, 如果你要排序的 Set 可用 TreeSet
for (int element : nonDuplicateArray) {
System.out.print(element + ", ");
}
cf :
http://werdna1222coldcodes.blogspot.tw/2012/02/javaarray.html
http://www.lslnet.com/linux/f/docs1/i63/big5411025.htm
沒有留言:
張貼留言