자바기초

Set계열 컬렉션

lby132 2021. 9. 24. 23:17

HashSet에서 hash값으로 관리하기 때문에 중복 데이터는 허용하지 않는다 그래서 remove를 할때 기초자료형들은 바로 지워지지만 참조 자료형들은 새로 만들어지기 때문에 사라지지 않는다.

set.remove("a"); // 바로 삭제됨

set.remove(new Student("이순신", 1)); // new를 쓰면 새로운 객체가 생성 되기 때문에 삭제 되지 않음

이렇게 객체를 remove 하려면 hashCode를 맞춰주어야 한다.

 

public class Map {

public static void main(String[] args) {

 

HashSet<Student> set = new HashSet<Student>();

 

set.add(new Student("이순신", 1));

set.add(new Student("홍길동", 12));

set.add(new Student("덕혜", 13));

 

Student student = new Student("이순신",1);

set.remove(student);

 

System.out.println(set.toString());

 

}

}

 

 

public class Student {

 

private String name;

private int grade;

 

public Student(String name, int grade) {

this.name = name;

this.grade = grade;

}

 

@Override

public String toString() {

return name + " : " + grade;  // 해쉬값으로 나오지만 이렇게 해주면 문자열로 제대로 반환해서 보여준다.

}

 

@Override

public boolean equals(Object obj) {

String comparValue = obj.toString();

String thisValue = toString();

return thisValue.equals(comparValue);  

}

 

@Override

public int hashCode() {

return toString().hashCode();

}

}

 

 

이렇게 해주면 제대로 삭제가 된다.

'자바기초' 카테고리의 다른 글

doGet, doPost  (0) 2021.09.26
Synchronized  (0) 2021.09.25
컬렉션  (0) 2021.09.24
StringBuffer  (0) 2021.09.23
싱글톤  (0) 2021.09.22