HashMap
21 Oct 2021 -
1 minute read
-
Map μΈν°νμ΄μ€ ꡬν
-
key - valueλ₯Ό μμΌλ‘ κ΄λ¦¬νλ λ©μλ ꡬν
-
κ²μμ μν μλ£κ΅¬μ‘°
-
keyλ₯Ό μ΄μ©νμ¬ κ°μ μ μ₯νκ³ κ·Έ keyλ₯Ό μ΄μ©νμ¬ κ°μ κΊΌλ΄μ€λ λ°©μ
-
hash μκ³ λ¦¬μ¦μΌλ‘ ꡬνλ¨
-
keyκ° λλ κ°μ²΄λ μ€λ³΅λ μ μμ > κ°μ²΄μ μ μΌμ± λΉκ΅λ₯Ό μν equals()λ©μλμ hashCode()λ©μλ ꡬνν΄μΌ ν¨
-
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 + "μ λλ€."; } @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; } }
-
MemberHashMap.java
import java.util.HashMap; import java.util.Iterator; public class MemberHashMap { private HashMap<Integer, Member> hashMap; // key = Integer, value = Member public MemberHashMap() { hashMap = new HashMap<Integer, Member>(); } public void addMember (Member member) { hashMap.put(member.getMemberId(), member); // add X / put O } public boolean removeMember (int memberId) { if (hashMap.containsKey(memberId)) { hashMap.remove(memberId); } System.out.println("ν΄λΉ μμ΄λκ° μμ΅λλ€."); return false; } public void showAllMember() { Iterator<Integer> ir = hashMap.keySet().iterator(); while (ir.hasNext()) { int key = ir.next(); Member member = hashMap.get(key); System.out.println(member); } } }
-
(Main Class) MemberHashMapTest.java
public class MemberHashMapTest { public static void main(String[] args) { MemberHashMap memberHashMap = new MemberHashMap(); Member member1 = new Member(101, "μ΄λ°€"); Member member2 = new Member(102, "κ°μλ²½"); Member member3 = new Member(103, "μ΅μμΉ¨"); memberHashMap.addMember(member1); memberHashMap.addMember(member2); memberHashMap.addMember(member3); memberHashMap.showAllMember(); } }
-
μΆλ ₯κ²°κ³Ό
μ΄λ°€ νμλμ μμ΄λλ 101μ λλ€. κ°μλ²½ νμλμ μμ΄λλ 102μ λλ€. μ΅μμΉ¨ νμλμ μμ΄λλ 103μ λλ€.
-