* Set 계열 특징 : 데이터만 저장가능 / 순서 유지 안함 /중복 객체 허용 안됨
HashSet hs1 = new HashSet();
hs1.add("반갑습니다.");
hs1.add(new String("반갑습니다."));
hs1.add(new String("여러분"));
hs1.add(new String("안녕하세요"));
hs1.add(new String("여러분"));
System.out.println(hs1);
>> 출력결과 [안녕하세요, 여러분, 반갑습니다.]
//->순서유지 안됨, 중복데이터(동일객체) 보관 불가
HashSet<Student> hs2 = new HashSet<>(); // <> 제네릭 설정해주면 타입 제한됨, 해당 객체 반환시 형변환 하지않아도됨
hs2.add(new Student("공유",43,80));
hs2.add(new Student("이도현",27,95));
hs2.add(new Student("차은우",25,100));
hs2.add(new Student("공유",43,80));
System.out.println(hs2);
>>출력결과 [Student [name=공유, age=43, score=80], Student [name=공유, age=43, score=80], ...
// 중복제거 X => 동일객체로 판단 안되고있기때문
// 동일객체 : 각 객체마다 hashCode 결과가 일치, equals 비교시 true 여야됨
System.out.println(new Student("공유",43,80).hashCode()); //971848845
System.out.println(new Student("공유",43,80).hashCode()); //1910163204
System.out.println(new Student("공유",43,80).equals(new Student("공유",43,80))); //false
위의 Student 공유 객체를 보면 hashCode와 불일치, equals 메소드 false출력되는 것을 확인할 수있다.
>>Object클래스의 hashCode와 equals메소드는 주소값을 비교하기때문에 두객체가 동일하지 않음
Student 클래스에 equals() 오버라이딩 => "실제 각 필드에 담긴 데이터" 들이 다 일치하면 true/ 그게아니면 false
Student 클래스에 hashCode() 오버라이딩 => "실제 각 필드에 담긴 데이터" 들이 일치하면 동일한 10진수 반환
-> 자동 오버라이딩 방법 : Shift+ Alt + S -》 Generate hashCode() and equals()
>> 오버라이딩 후 출력결과
System.out.println(new Student("공유",43,80).hashCode()); //44201647
System.out.println(new Student("공유",43,80).hashCode()); //44201647
System.out.println(new Student("공유",43,80).equals(new Student("공유",43,80))); //true
** HashSet에 담긴 모든 객체들을 순차적으로 접근하기
방법 1. for문 사용 가능(단, 향상된 for문으로만 가능)
for(Student s : hs2) {
System.out.println(s);
}
방법2. ArrayList에 옮겨담은 후 ArrayList반복문 돌려서 출력
//>>ArrayList에 옮겨담기 1. addAll메소드 이용
ArrayList<Student> list1 = new ArrayList<>();
list1.addAll(hs2);
//>>ArrayList에 옮겨담기 2. ArrayList생성시 통채로 추가하기
ArrayList<Student> list2 = new ArrayList<>(hs2);
for(int i=0;i<list2.size();i++) {
System.out.println(list2.get(i));
}
방법3. Iterator(반복자)이용하여 순차적으로 접근
Iterator<Student> it = hs2.iterator(); //hs2에 담겨있는 객체들을 => Iterator 에 담는 과정
while(it.hasNext())/*it공간으로부터 뽑을 객체가 있을경우*/ {
Student s = it.next();
System.out.println(s);
}
StringTokenizer와 비슷한 개념
이후 it.next(); 를 출력하면 예외 (java.util.NoSuchElementException 더이상의 요소없음 )발생
'JAVA' 카테고리의 다른 글
13.Collection_Map_Properties (0) | 2022.11.10 |
---|---|
13.Collection_Map_HashMap (0) | 2022.11.10 |
13. Collection_ List_ArrayList 와 Generic (0) | 2022.11.09 |
13_ Collection _Collection과 List_ArrayList (0) | 2022.11.08 |
12. IO (IntputOutput) _객체 배열 입출력 (0) | 2022.11.08 |