본문 바로가기

Java

자바 컬렉션 - set

HashSet의 특징
  • 중복안됨
  • 순서대로 출력 안함
HashSet<String> 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);
[반갑습니다, 안녕하세요, 여러분]
  • String은 실제 담긴 문자열을 가지고 비교하며 HashSet에 입력 될 때 중복 값은 하나로 처리된다
HashSet<Student> hs2 = new HashSet<Student>();

hs2.add(new Student("공유", 43, 100));
hs2.add(new Student("차은우", 26, 85));
hs2.add(new Student("주지훈", 24, 20));
hs2.add(new Student("공유", 43, 100));
  • 모든 객체는 생성시 다 다른 주소 값을 가지고 있기 때문에 주소 값을 따지는 HashSet 안에서 중복이 일어나지 않는다
  • 또한, 인덱스의 개념이 없어서 내가 쓴 순서대로 저장이 되지 않는다
동일 객체 : 각 객체마다 hashCode() 호출 결과가 일치하고, equals() 비교시 true 일 경우
hashCode 와 equals를 오버라이딩 해주어 같은 값의 객체를 동일 객체로 인식하게 만들기
package com.kh.chap02_set.part01_hashSet.model.vo;

public class Student {
	private String name;
	private int age;
	private int score;

	public Student() {

	}

	public Student(String name, int age, int score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}

	protected String getName() {
		return name;
	}

	protected void setName(String name) {
		this.name = name;
	}

	protected int getAge() {
		return age;
	}

	protected void setAge(int age) {
		this.age = age;
	}

	protected int getScore() {
		return score;
	}

	protected void setScore(int score) {
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
	}
	/*
	 * @Override public int hashCode() { 
	 * // 모든 필드에 담긴 값이 일치하면 동일한 hashCode 반환 하도록 재정
	 * 
	 * String str = name + age + score; 
	 * // "공유43100", "차은우2685", "주지훈2420", "공유43100" 
	 * 
	 * return str.hashCode(); 
	 * // 문자열을 가지고 주소를 만들게 끔 바꿔 준겨, 따라서 글자가 같으면 같은 주소 값을 갖게 함
	 * 
	 * }
	 * 
	 * @Override public boolean equals(Object obj) {
	 * 
	 * // 현재 객체와 전달 받은 객체의 각 필드 값이 모두 일치하면 true, 
	 * // 하나로 일치하지 않으면 false 반환 
	 * // this(현재 객체) vs obj(전달 받은 객체 : 매개변수) 
	 * // this.name vs obj.name 일치하는지 보자 
	 * // this.age vs obj.age 
	 * // this.score vs obj.score
	 * 
	 * Student other = (Student) obj;
	 * 
	 * if (this.name.equals(other.name) && this.age == other.age && this.score == other.score) { 
	 * return true; }
	 * else {
	 * return false; }
	 */

	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + score;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (score != other.score)
			return false;
		return true;
	}

}
  • Source - Generates hashCode() and equals()
hashSet에 담긴 모든 객체들 불러오기

1. for문 사용 가능 (향상된 for문(for each)만 사용 가능!!!!!!)

for (Student s : hs2) {
		// 제네릭 설정 안 하면 Object 형으로 선언해야 함
		System.out.println(s);
	}
        
/*
* 일반 for문은 Sysout 안에 쓸 요소가 없어서 사용 불가 for (int i = 0; i < hs2.size(); i++) {
* System.out.println(); }
*/

2. ArrayList에 담아준 다음 ArrayList를 반복문 돌려가면서 접근

ArrayList에 담는 첫번째 방법 : ArrayList 생성 후 addAll() 메소드 이용해서 통째로 추가하기
ArrayList<Student> list = new ArrayList<Student>();
list.addAll(hs2);
ArrayList에 담는 두번째 방법 : ArrayList를 생성과 동시에 통째로 추가하기
ArrayList<Student> list2 = new ArrayList<Student>(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()) { // 어떤 요소가 있을 때 까지 계속 돌아감
			Student s = it.next(); // iterator에서 가지고 나와서
			System.out.println(s); // 출력
		}

'Java' 카테고리의 다른 글

자바 컬렉션 - propertie  (0) 2022.11.24
자바 컬렉션 - Map  (0) 2022.11.23
자바 컬렉션 - list  (0) 2022.11.22
자바 컬렉션 : ArrayList 제네릭  (0) 2022.11.20
자바 컬렉션 : ArrayList  (0) 2022.11.20