Java:移除陣列Array中重複的值

參考:https://www.ewdna.com/2012/02/javaarray.html

1 package werdna1222coldcodes.blogspot.com.demo.array;
 2 
 3 import java.text.ParseException;
 4 import java.util.HashSet;
 5 import java.util.Set;
 6 
 7 public class ArrayRemoveDuplicateDemo {
 8 
 9     public static void main(String[] args) throws ParseException {
10 
11         // 建立有重複項目之 int array
12         int duplicateArray[] = { 4, 2, 5, 1, 5, 2, 4, 3 };
13         
14         // 利用 Set 的特性,將所有項目放入 Set 
15         中即可移除重複的項目
16         Set<Integer> intSet = new HashSet<Integer>();
17         for (int element : duplicateArray) {
18             intSet.add(element);
19         }
20 
21         // intSet.size() 為不重複項目的個數
22         int nonDuplicateArray[] = new int[intSet.size()];
23 
24         // 將 Set 中的項目取出放到 nonDuplicateArray 中
25         // 這裡也可以利用 iterator 來達成
26         Object[] tempArray = intSet.toArray();
27         for (int i = 0; i < tempArray.length; i++) {
28             nonDuplicateArray[i] = (Integer) tempArray[i];
29         }
30 
31         // 輸出結果:1, 2, 3, 4, 5, 
32         for (int element : nonDuplicateArray) {
33             System.out.print(element + ", ");
34         }
35     }
36 }