package ch02_set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ExHashSet {
public static void main(String[] args) {
// HashSet<Member> hs = new HashSet<>();
Set<Member> hs = new HashSet<>();
Member memA = new Member("유재석", 50);
Member memB = new Member("유재석", 50);
System.out.println(memA.hashCode());
System.out.println(memB.hashCode());
hs.add(memA);
hs.add(memB);
hs.add(new Member("김종국",45));
hs.add(new Member("김종국",45));
System.out.println(hs);
System.out.println("데이터 수 : " + hs.size());
System.out.println();
for(Member man : hs) {
System.out.println(man);
}
System.out.println();
Iterator<Member> it = hs.iterator();
String dname = "유재석";
while(it.hasNext()) {
Member man = it.next();
if(man.getName().equals(dname)) {
System.out.println("찾았다...");
it.remove();
}
}
System.out.println();
System.out.println(hs);
}
}
package ch02_set;
public class Member {
private String name;
private int age;
public Member(String name, int age ) { this.name = name; this.age = age;}
public String getName() { return name; }
public void setName(String name) { this.name =name;}
public int getAge() {return age;}
public void setAge(int age) {this.age=age;}
public int hashcode() {
return name.hashCode();
}
public boolean equals(Object obj) {
if(obj instanceof Member) {
Member tmp = (Member)obj;
if(!name.equals(tmp.name)) {
return false;
}
if(!(age == tmp.age)) {
return false;
}
return true;
}
return false;
}
public String toString() {
return name + " - " + age;
}
}
package ch02_set;
public class Person {
/*
* Person class 를 구현하세요
* → 이름, 전화번호의 관리가 가능합니다
*/
private String name;
private String phonenumber;
public Person(String name, String phonenumber) {
this.name=name; this.phonenumber=phonenumber;
}
public int hashCode() { return name.hashCode() + phonenumber.hashCode(); }
public String getname() {return name;}
public void setname(String name) {this.name = name;}
public String getphonenumber() {return phonenumber;}
public void setphonenumber(String phonenumber) {this.phonenumber = phonenumber;}
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person tmp = (Person)obj;
if(!name.equals(tmp.name))
return false;
if(!phonenumber.equals(tmp.phonenumber))
return false;
return true;
}
return false;
}
public String toString() {
return name + " / " + phonenumber;
}
}