HashSet
21 Oct 2021 -
1 minute read
-
HashSet ν΄λμ€λ Set μΈν°νμ΄μ€ ꡬν > μμλ₯Ό μμμ μκ΄μμ΄ μ μ₯, μ€λ³΅λ κ°μ μ μ₯νμ§ μμ
-
HashSetμμ add() λ©μλλ₯Ό μ¬μ©νμ¬ μ€λ³΅ μμ΄ μλ‘μ΄ μμλ₯Ό μΆκ°νκΈ° μν΄μλ hashCode()μ equals() λ©μλλ₯Ό μ€λ²λΌμ΄λ©ν΄μΌ ν¨
-
ex)
-
Member.java
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 + "μ λλ€."; } // 맀κ°λ³μλ‘ λμ΄μ¨ κ²μ΄ λμ κ°μμ§λ₯Ό νμΈν΄μ£Όλ equalsμ hashcode ꡬν @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; } else return false; } return false; }
-
MemberHashSet.java
import java.util.HashSet; public class MemberHashSet { private HashSet<Member> hashSet; public MemberHashSet() { hashSet = new HashSet<>(); } public MemberHashSet(int size) { hashSet = new HashSet<>(size); } public void addMember(Member member) { hashSet.add(member); } public boolean removeMember(int memberId) { for (int i = 0; i < arrayList.size(); i++) { Member member = arrayList.get(i); int tempId = member.getMemberId(); if (tempId == memberId) { arrayList.remove(i); return true; } } System.out.println("ν΄λΉ μμ΄λκ° μ‘΄μ¬νμ§ μμ΅λλ€."); return false; } public void showAllMember() { for (Member member : hashSet) { System.out.println(member); } } }
-
MemberHashSetMain.java
public class MemberHashSetMain { public static void main(String[] args) { MemberHashSet memberHashSet = new MemberHashSet(); Member member1 = new Member(101, "μ΄λ°€"); Member member2 = new Member(102, "κ°μλ²½"); Member member3 = new Member(103, "μ΅μμΉ¨"); memberHashSet.addMember(member1); memberHashSet.addMember(member2); memberHashSet.addMember(member3); Member member4 = new Member(103, "μ€μ λ "); // hashCode() / equals() λ©μλ μ¬μ© ν΄ μ€λ³΅ μ¬λΆλ₯Ό 체ν¬ν΄μ€μΌ ν¨ memberHashSet.addMember(member4); memberHashSet.showAllMember(); } }
-
μΆλ ₯κ²°κ³Ό
μ΄λ°€ νμλμ μμ΄λλ 101μ λλ€. κ°μλ²½ νμλμ μμ΄λλ 102μ λλ€. μ΅μμΉ¨ νμλμ μμ΄λλ 103μ λλ€.
-