Set 순서가 없고, 중복을 허용하지 않는다.
Set인터페이스를 구현한 클래스로는 HashSet←LinkedHashSet, TreeSet이 있다.
boolean add(Object o)를 이용하여 저장한다.
저장하기 전에 기존에 HashSet에 같은 객체가 있는지 확인한다. 같은 객체가 없으면 저장하고 true를 반환한다. 있으면 저장하지 않고 false를 반환한다.
public class HashSetEx1 {
public static void main(String[] args) {
Object[] objArr = {"1", new Integer(1), "2" ,"2","4","3","3","4","4"};
Set set = new HashSet();
for(int i=0; i<objArr.length; i++){
set.add(objArr[i]);
}
System.out.println(set); //[1,1,2,3,4]
}
}
"1"과 Integer(1)은 다른 객체이기 때문에 각각 추가하고, 중복되는 것은 set에 추가되지 않는다.
public class HashSetEx1 {
public static void main(String[] args) {
Object[] objArr = {"1", new Integer(1), "2" ,"2","4","3"};
Set set = new HashSet();
for(int i=0; i<6; i++){
set.add((int)(Math.random()*45)+1);
}
List list = new LinkedList(set); // set은 Collections의 sort를 사용할 수 없다.
Collections.sort(list);
System.out.println(list);
}
}
정렬을 위해서 set을 List로 변환하여 Collections의 sort(List list)메소드를 사용하였다.
public class Bingo {
public static void main(String[] args) {
Set set = new HashSet();
Set set2 = new LinkedHashSet();
int[][] board = new int[5][5];
for(int i=0; set.size()<25; i++){
set.add((int)(Math.random()*50)+1+"");
}
Iterator it = set.iterator();
for(int i=0; i<board.length; i++){
for(int j=0; j<board[i].length; j++){
board[i][j]=Integer.parseInt((String)it.next());
System.out.print((board[i][j]<10?" ":" ")+board[i][j]); // 칸수 맞추기위해
}
System.out.println();
}
}
}
HashSet은 저장된 순서를 보장하지 않고, 자체적인 저장방식에 따라 순서가 결정되기 때문에 같은 숫자가 비슷한 위치에서 계속 나오게 된다. 그러므로 LinkedHashSet을 쓰는것이 적합하다.
HashSet의 add메소드는 새로운 요소를 추가하기 전에 equals()와 hashCode()메소드롤 호출하기 때문에 목적에 맞게 오버라이딩해야한다.
public int hashCode(){
return (name+age).hashCode();
}
// jdk 1.8부터 Objects클래스의 hash()를 이용하여 작성할 수 있다.
public int hashCode(){
return Objects.hash(name, age); // int hash(Object... values)
}
가능하면 후자의 코드를 사용하는것이 좋다고 한다.