Skip to content

Commit d685c4c

Browse files
KhArtNJavaenhorse
authored andcommitted
Добавлен пример кода с иллюстрацией для IdentityHashMap и HashMap
1 parent 18012a0 commit d685c4c

1 file changed

Lines changed: 111 additions & 0 deletions

File tree

jcf.md

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,117 @@ private static class Node<E> {
533533

534534
`IdentityHashMap` может применяться для реализации сериализации/клонирования. При выполнении подобных алгоритмов программе необходимо обслуживать хэш-таблицу со всеми ссылками на объекты, которые уже были обработаны. Такая структура не должна рассматривать уникальные объекты как равные, даже если метод `equals()` возвращает `true`.
535535

536+
Пример кода:
537+
```java
538+
import java.util.HashMap;
539+
import java.util.IdentityHashMap;
540+
import java.util.Map;
541+
542+
public class Q2 {
543+
544+
public static void main(String[] args) {
545+
546+
Q2 q = new Q2();
547+
q.testHashMapAndIdentityHashMap();
548+
549+
}
550+
551+
private void testHashMapAndIdentityHashMap() {
552+
CreditCard visa = new CreditCard("VISA", "04/12/2019");
553+
554+
Map<CreditCard, String> cardToExpiry = new HashMap<>();
555+
Map<CreditCard, String> cardToExpiryIdenity = new IdentityHashMap<>();
556+
557+
System.out.println("adding to HM");
558+
// inserting objects to HashMap
559+
cardToExpiry.put(visa, visa.getExpiryDate());
560+
561+
// inserting objects to IdentityHashMap
562+
cardToExpiryIdenity.put(visa, visa.getExpiryDate());
563+
System.out.println("adding to IHM");
564+
565+
System.out.println("before modifying keys");
566+
String result = cardToExpiry.get(visa) != null ? "Yes" : "No";
567+
System.out.println("Does VISA card exists in HashMap? " + result);
568+
569+
result = cardToExpiryIdenity.get(visa) != null ? "Yes" : "No";
570+
System.out.println("Does VISA card exists in IdenityHashMap? " + result);
571+
572+
// modifying value object
573+
visa.setExpiryDate("02/11/2030");
574+
575+
System.out.println("after modifying keys");
576+
result = cardToExpiry.get(visa) != null ? "Yes" : "No";
577+
System.out.println("Does VISA card exists in HashMap? " + result);
578+
579+
result = cardToExpiryIdenity.get(visa) != null ? "Yes" : "No";
580+
System.out.println("Does VISA card exists in IdenityHashMap? " + result);
581+
582+
System.out.println("cardToExpiry.containsKey");
583+
System.out.println(cardToExpiry.containsKey(visa));
584+
System.out.println("cardToExpiryIdenity.containsKey");
585+
System.out.println(cardToExpiryIdenity.containsKey(visa));
586+
}
587+
588+
}
589+
590+
class CreditCard {
591+
private String issuer;
592+
private String expiryDate;
593+
594+
public CreditCard(String issuer, String expiryDate) {
595+
this.issuer = issuer;
596+
this.expiryDate = expiryDate;
597+
}
598+
599+
public String getIssuer() {
600+
return issuer;
601+
}
602+
603+
public String getExpiryDate() {
604+
return expiryDate;
605+
}
606+
607+
public void setExpiryDate(String expiry) {
608+
this.expiryDate = expiry;
609+
}
610+
611+
@Override
612+
public int hashCode() {
613+
final int prime = 31;
614+
int result = 1;
615+
result = prime * result + ((expiryDate == null) ? 0 : expiryDate.hashCode());
616+
result = prime * result + ((issuer == null) ? 0 : issuer.hashCode());
617+
System.out.println("hashCode = " + result);
618+
return result;
619+
}
620+
621+
@Override
622+
public boolean equals(Object obj) {
623+
System.out.println("equals !!! ");
624+
if (this == obj)
625+
return true;
626+
if (obj == null)
627+
return false;
628+
if (getClass() != obj.getClass())
629+
return false;
630+
CreditCard other = (CreditCard) obj;
631+
if (expiryDate == null) {
632+
if (other.expiryDate != null)
633+
return false;
634+
} else if (!expiryDate.equals(other.expiryDate))
635+
return false;
636+
if (issuer == null) {
637+
if (other.issuer != null)
638+
return false;
639+
} else if (!issuer.equals(other.issuer))
640+
return false;
641+
return true;
642+
}
643+
644+
}
645+
```
646+
536647
[к оглавлению](#java-collections-framework)
537648

538649
## В чем разница между `HashMap` и `WeakHashMap`? Для чего используется `WeakHashMap`?

0 commit comments

Comments
 (0)