java - MemberHashSet

imjingu·2023년 9월 5일
0

개발공부

목록 보기
459/481
package chapter20230905.HashSet;

public class Member {
	private int memberID;
	private String memberName;

	public Member(int memberID, String memberName) {
		this.memberID = memberID;
		this.memberName = memberName;
	}

	public int getMemberID() {
		return memberID;
	}


	public void setMemberID(int memberID) {
		this.memberID = memberID;
	}


	public String getMemberName() {
		return memberName;
	}


	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}
	
	@Override
	public String toString() {
		return memberName + "회원님의 아이디는 " + memberID + " 입니다.";
	}
	
	@Override
	public int hashCode() { // 
		return memberID;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Member) {
			Member member = (Member)obj;
			if(this.memberID == member.memberID)
				return true;
		}
		return false;
	}

}

package chapter20230905.HashSet;
import java.util.*;

public class MemberHashSet {
	private HashSet<Member> hashSet; // HashSet 선언
	
	public MemberHashSet() {
		hashSet = new HashSet<>(); // HashSet 생성
	}
	
	public void addMember(Member member) {
		hashSet.add(member); // HashSet에 회원 추가
	}
	
	public boolean removeMemeber(int memberId) {
		// 매개변수로 받은 회원 아이디에 해당하는 회원 삭제
		
//		Iterator<Member> iterator = hashSet.iterator(); // iterator를 활용해 순회함
//		while(iterator.hasNext()) {
//			Member member = iterator.next(); // 회원을 하나씩 가져와서
//			int tempId = member.getMemberID(); // 아이디 비교
//			if(tempId == memberId) { // 같은 아이디인 경우
//				hashSet.remove(member); // 회원 삭제
//				return true;
//			}
//		}
		for(Member member : hashSet) {
			int tempId = member.getMemberID(); // 아이디 비교
			if(tempId == memberId) { // 같은 아이디인 경우
				hashSet.remove(member); // 회원 삭제
				return true;
			}	
		}
		System.out.println(memberId + "가 존재하지 않습니다.");
		return false;
	}
	public void showAllMember() { // 모든 회원 출력
		for(Member member : hashSet) {
			System.out.println(member);
		}
		System.out.println();
	}
	
}

package chapter20230905.HashSet;

public class MemberHashSetTest {
	public static void main(String[] args) {
		MemberHashSet memberHashSet = new MemberHashSet();
	
	    Member memberLee = new Member(1001, "이지원");
	    Member memberSon = new Member(1002, "손민국");
	    Member memberPark = new Member(1003, "박서훤");
	
	    memberHashSet.addMember(memberLee);
	    memberHashSet.addMember(memberSon);
	    memberHashSet.addMember(memberPark);
	    memberHashSet.showAllMember();
	
	    memberHashSet.addMember(memberLee); // 중복된 객체 저장.
	    memberHashSet.showAllMember(); // 중복된 객체는 저장되지 않음.
	
	    Member memberHong = new Member(1003, "홍길동");  //1003 아이디 중복 회원 추가.
	    memberHashSet.addMember(memberHong);
	    memberHashSet.showAllMember();
	    
	    memberHashSet.removeMemeber(1002);
	    memberHashSet.showAllMember();
	}
}

0개의 댓글