Student Class
public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } //================================================= //추가 HashSet에 키로 사용할 필드를 Override 한다. @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if(!(obj instanceof Student)) { return false; } Student s = (Student)obj; return name.equals(s.name); } //================================================= }
Main Class
import java.util.HashSet; public class MainTest { private static HashSet hashset = new HashSet(); public static void main(String[] args) { hashset.add(new Student("홍길동", 25)); hashset.add(new Student("똘이장군", 12)); hashset.add(new Student("일지매", 23)); hashset.add(new Student("똘이장군", 15)); System.out.println("Student Count : " + hashset.size()); for (Student std : hashset) { System.out.println(std.getName()); } } }
결과값
설명
'Common > Java' 카테고리의 다른 글
String format 사용법 (0) | 2014.12.18 |
---|---|
한글 Encoding 문제 해결 (0) | 2014.12.10 |
PriorityQueue, Comparator (0) | 2014.05.23 |
UniCode를 byte단위로 계산 (0) | 2014.05.08 |