그만큼 신원해시맵 구현하다 지도 인터페이스를 사용하여 해시테이블 키(및 값)를 비교할 때 객체 동등성 대신 참조 동등성을 사용합니다. 이 클래스는 범용 Map 구현이 아닙니다. 이 클래스는 Map 인터페이스를 구현하지만 객체를 비교할 때 equals() 메서드의 사용을 요구하는 Map의 일반 계약을 의도적으로 위반합니다. 이 클래스는 사용자가 참조를 통해 객체를 비교해야 할 때 사용됩니다. 에 속한다 java.util 패키지.
IdentityHashMap의 특징
- == 연산자를 사용하는 == 메서드를 사용하는 대신 참조 동등성을 따릅니다.
- 동기화되지 않았으므로 외부에서 동기화해야 합니다.
- 반복자는 빠른 실패 던지기입니다. ConcurrentModificationException 반복하는 동안 수정하려고 합니다.
- 이 클래스는 시스템 ID 해시 함수(System.identityHashCode(Object))가 요소를 버킷 간에 적절하게 분산시킨다고 가정하여 기본 작업(가져오기 및 넣기)에 대해 일정한 시간 성능을 제공합니다. IdentityHashMap은 hashCode() 메서드를 사용하지 않고 System.identityHashCode() 메서드를 사용합니다. 이는 이제 매핑이 IdentityHashMap 내에 저장될 때 해시 코드가 변경될 가능성이 있는 변경 가능한 객체를 Map의 키로 사용할 수 있기 때문에 중요한 차이점입니다.
선언:
공개 클래스 IdentityHashMap
AbstractMap을 확장합니다. 지도 구현 직렬화 가능 복제 가능
여기 케이 주요 객체 유형이며 다섯 값은 객체 유형입니다.
Java에서 IdentityHashMap은 Map 인터페이스를 구현하는 클래스입니다. IdentityHashMap은 키를 비교할 때 객체 동등성 대신 참조 동등성을 사용한다는 점을 제외하면 HashMap 클래스와 유사합니다.
HashMap은 equals() 메소드를 사용하여 키를 비교하는 반면 IdentityHashMap은 == 연산자를 사용하여 키를 비교합니다. 이는 IdentityHashMap에서 두 키가 내용 측면에서 동일하지 않고 동일한 객체인 경우에만 동일한 것으로 간주된다는 것을 의미합니다.
자바가 포함된 mvc
다음은 Java에서 IdentityHashMap을 사용하는 방법의 예입니다.
Javaimport java.util.IdentityHashMap; public class Example { public static void main(String[] args) { IdentityHashMap<String Integer> identityHashMap = new IdentityHashMap<>(); identityHashMap.put('A' 1); identityHashMap.put(new String('A') 2); System.out.println(identityHashMap.size()); // 2 System.out.println(identityHashMap.get('A')); // 1 } }
산출;
2
1
Java의 IdentityHashMap 클래스는 키(및 값)를 비교할 때 객체 동등성 대신 참조 동등성을 사용하는 Map 인터페이스의 해시 테이블 기반 구현입니다.
HashMap보다 IdentityHashMap을 사용하면 다음과 같은 이점이 있습니다.
- 빠른 조회: IdentityHashMap은 비교를 위해 참조 동등성을 사용하므로 객체 동등성을 사용하는 HashMap에 비해 조회 속도가 더 빠릅니다.
- 개체 인스턴스를 비교하는 데 유용합니다. IdentityHashMap은 개체 값이 아닌 개체 인스턴스를 비교하려는 상황에 유용합니다.
IdentityHashMap 사용의 단점:
- 더 많은 메모리 사용: IdentityHashMap은 객체에 대한 참조를 저장해야 하기 때문에 HashMap에 비해 더 많은 메모리를 사용합니다.
- 모든 사용 사례에 적합하지 않음: IdentityHashMap은 모든 사용 사례에 적합하지 않으며 특정 상황에서 예기치 않은 동작이 발생할 수 있으므로 주의해서 사용해야 합니다.
IdentityHashMap의 계층 구조
구현합니다 직렬화 가능 복제 가능 지도
예:
Java// Java code to demonstrate IdentityHashMap import java.util.Map; import java.util.HashMap; import java.util.IdentityHashMap; public class IdentityHashMapExample { public static void main(String[] args) { // creating an instance of IdentityHashMap Map<String String> ihm = new IdentityHashMap<>(); // Putting key and value pair // in a IdentityHashMap Object ihm.put('ihmkey''ihmvalue'); ihm.put(new String('ihmkey')'ihmvalue1'); // ihm.size() will print 2 since it // compares the objects by reference System.out.println('Size of IdentityHashMap--'+ihm.size()); } }
산출
Size of IdentityHashMap--2
IdentityHashMap 생성자
우리는 신원해시맵 두 가지 방법으로:
IdentityHashMapihm = new IdentityHashMap (); (or) Map hm = new IdentityHashMap ();
1. 아이덴티티해시맵(): 기본 예상 최대 크기를 사용하여 새로운 빈 ID 해시 맵을 생성합니다.
신원해시맵
그 = 새로운 IdentityHashMap ();
2. IdentityHashMap(int 예상MaxSize): 지정된 예상 최대 크기로 새로운 빈 맵을 생성합니다.
신원해시맵
ihm = new IdentityHashMap(int ExpectMaxSize);
3. IdentityHashMap(맵 m): 지정된 맵의 키-값 매핑을 포함하는 새로운 ID 해시 맵을 생성합니다.
신원해시맵
ihm = new IdentityHashMap(Map m); 미션 임파서블 모든 영화
IdentityHashMap의 기본 작업
1. 요소 추가
IdentityHashMap에 매핑을 삽입하거나 추가하려면 놓다() 그리고 풋올() 행동 양식. put()은 특정 키와 특정 맵에 매핑되는 값을 삽입할 수 있습니다. 기존 키가 전달되면 이전 값이 새 값으로 대체됩니다. putAll()은 모든 요소, 즉 한 맵에서 다른 맵으로의 매핑을 복사합니다.
Java// Java code to illustrate // adding elements to IdentityHashMap import java.util.*; public class AddingElementsToIdentityHashMap { public static void main(String[] args) { // Creating an empty IdentityHashMap Map<Integer String> identity_hash = new IdentityHashMap<Integer String>(); // Mapping string values to int keys // using put() method identity_hash.put(10 'Geeks'); identity_hash.put(15 '4'); identity_hash.put(20 'Geeks'); identity_hash.put(25 'Welcomes'); identity_hash.put(30 'You'); // Displaying the IdentityHashMap System.out.println('Initial Mappings are: ' + identity_hash); // Inserting existing key along with new value // previous value gets returned and stored in // returned_value String returned_value = (String)identity_hash.put(20 'All'); // Verifying the returned value System.out.println('Returned value is: ' + returned_value); // Displaying the new map System.out.println('New map is: ' + identity_hash); // Creating a new Identityhash map and copying Map<Integer String> new_Identityhash_map = new IdentityHashMap<Integer String>(); new_Identityhash_map.putAll(identity_hash); // Displaying the final IdentityHashMap System.out.println('The new map: ' + new_Identityhash_map); } }
산출
Initial Mappings are: {30=You 10=Geeks 15=4 25=Welcomes 20=Geeks} Returned value is: Geeks New map is: {30=You 10=Geeks 15=4 25=Welcomes 20=All} The new map: {30=You 10=Geeks 15=4 25=Welcomes 20=All} 2. 요소 제거
매핑을 제거하기 위해 우리는 제거하다() IdentityHashMap 클래스의 내장 메소드이며 맵에서 특정 키의 매핑을 제거하는 데 사용됩니다.
// Java code to illustrate removing // elements from IdentityHashMap import java.util.*; public class RemovingMappingsFromIdentityHashMap { public static void main(String[] args) { // Creating an empty IdentityHashMap Map<Integer String> Identity_hash = new IdentityHashMap<Integer String>(); // Mapping string values to int keys Identity_hash.put(10 'Geeks'); Identity_hash.put(15 '4'); Identity_hash.put(20 'Geeks'); Identity_hash.put(25 'Welcomes'); Identity_hash.put(30 'You'); // Displaying the IdentityHashMap System.out.println('Initial Mappings are: ' + Identity_hash); // Removing the existing key mapping String returned_value = (String)Identity_hash.remove(20); // Verifying the returned value System.out.println('Returned value is: ' + returned_value); // Displaying the new map System.out.println('New map is: ' + Identity_hash); } }
산출
Initial Mappings are: {30=You 10=Geeks 15=4 25=Welcomes 20=Geeks} Returned value is: Geeks New map is: {30=You 10=Geeks 15=4 25=Welcomes} 3. 요소에 접근하기
다음을 사용하여 IdentityHashMap의 요소에 액세스할 수 있습니다. 얻다() 방법에 대한 예는 아래에 나와 있습니다.
Java// Java code to illustrate the accessing // elements from IdentityHashMap import java.util.*; public class AccessingElementsFromIdentityHashMap { public static void main(String[] args) { // Creating an empty IdentityHashMap Map<Integer String> identity_hash = new IdentityHashMap<Integer String>(); // Mapping string values to int keys identity_hash.put(10 'Geeks'); identity_hash.put(15 '4'); identity_hash.put(20 'Geeks'); identity_hash.put(25 'Welcomes'); identity_hash.put(30 'You'); // Displaying the IdentityHashMap System.out.println('Initial Mappings are: ' + identity_hash); // Getting the value of 25 System.out.println('The Value is: ' + identity_hash.get(25)); // Getting the value of 10 System.out.println('The Value is: ' + identity_hash.get(10)); // Using keySet() to get the set view of keys System.out.println('The set is: ' + identity_hash.keySet()); // Using entrySet() to get the set view System.out.println('The set is: ' + identity_hash.entrySet()); } }
산출
Initial Mappings are: {30=You 10=Geeks 15=4 25=Welcomes 20=Geeks} The Value is: Welcomes The Value is: Geeks The set is: [30 10 15 25 20] The set is: [30=You 10=Geeks 15=4 25=Welcomes 20=Geeks] 4. 횡단
Iterator 인터페이스를 사용하여 컬렉션 프레임워크의 모든 구조를 탐색할 수 있습니다. Iterator는 한 가지 유형의 데이터로 작동하므로 Entry를 사용합니다.< ? ? >두 가지 개별 유형을 호환 가능한 형식으로 해결합니다. 그런 다음 next() 메서드를 사용하여 IdentityHashMap의 요소를 인쇄합니다.
// Java code to illustrate the // iterating over IdentityHashmap import java.util.*; public class IteratingIdentityHashMap { public static void main(String[] args) { // Creating an empty IdentityHashMap IdentityHashMap<Integer String> identity_hash = new IdentityHashMap<Integer String>(); // Mapping string values to int keys identity_hash.put(10 'Geeks'); identity_hash.put(15 '4'); identity_hash.put(20 'Geeks'); identity_hash.put(25 'Welcomes'); identity_hash.put(30 'You'); // Displaying the IdentityHashMap System.out.println('Initial Mappings are: ' + identity_hash); // Create an Iterator over the // IdentityHashMap Iterator<IdentityHashMap.Entry<Integer String> > itr = identity_hash.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { IdentityHashMap.Entry<Integer String> entry = itr.next(); System.out.println('Key = ' + entry.getKey() + ' Value = ' + entry.getValue()); } } }
산출
Initial Mappings are: {30=You 10=Geeks 15=4 25=Welcomes 20=Geeks} Key = 30 Value = You Key = 10 Value = Geeks Key = 15 Value = 4 Key = 25 Value = Welcomes Key = 20 Value = Geeks 동기화된 IdentityHashMap
java 문자열을 int로 캐스트
여러 스레드가 동시에 ID 해시 맵에 액세스하고 스레드 중 하나 이상이 구조적으로 맵을 수정하는 경우 외부에서 동기화되어야 합니다. (구조적 수정은 하나 이상의 매핑을 추가하거나 삭제하는 모든 작업입니다. 단순히 인스턴스에 이미 포함된 키와 관련된 값을 변경하는 것은 구조적 수정이 아닙니다.) 이는 일반적으로 맵을 자연스럽게 캡슐화하는 일부 객체를 동기화하여 수행됩니다. 그러한 객체가 존재하지 않으면 지도는 다음을 사용하여 '래핑'되어야 합니다. Collections.synchronizedMap 방법. 이는 실수로 지도에 대한 비동기화 액세스를 방지하기 위해 생성 시 수행하는 것이 가장 좋습니다.
맵 m = Collections.synchronizedMap(new IdentityHashMap(...));
IdentityHashMap의 메서드
- IdentityHashMap은 키와 값을 비교하기 위해 항등 연산자 '=='를 사용하고, HashMap은 Map 내부의 키와 값을 비교하기 위해 equals 메소드를 사용합니다.
- IdentityHashMap은 Equals()를 사용하지 않기 때문에 비용이 많이 드는 Equals()를 사용하는 객체의 경우 HashMap보다 비교적 빠릅니다.
- IdentityHashMap은 equals()에 의존하지 않기 때문에 키를 변경할 수 없도록 요구하지 않습니다.
방법 | 설명 |
|---|---|
| 분명한() | 이 지도에서 모든 매핑을 제거합니다. |
| 클론() | 이 ID 해시 맵의 얕은 복사본을 반환합니다. 키와 값 자체는 복제되지 않습니다. |
| containKey?(객체 키) | 지정된 개체 참조가 이 ID 해시 맵의 키인지 여부를 테스트합니다. |
| ContainsValue?(객체 값) | 지정된 개체 참조가 이 ID 해시 맵의 값인지 테스트합니다. |
| 엔트리셋() | 다음을 반환합니다. 세트 이 지도에 포함된 매핑 보기입니다. |
| 같음?(객체 o) | 지정된 개체가 이 맵과 동일한지 비교합니다. |
| get?(객체 키) | 지정된 키가 매핑된 값을 반환하거나, 이 맵에 키에 대한 매핑이 포함되어 있지 않으면 null을 반환합니다. |
| 해시코드() | 이 지도의 해시 코드 값을 반환합니다. |
| 비어있음() | 이 ID 해시 맵에 키-값 매핑이 없으면 true를 반환합니다. |
| 키세트() | 이 맵에 포함된 키의 ID 기반 세트 뷰를 반환합니다. |
| 넣어?(K 키 V 값) | 지정된 값을 이 ID 해시 맵의 지정된 키와 연결합니다. |
| putAll?(지도 extends K?? extends V>중) | 지정된 맵의 모든 매핑을 이 맵에 복사합니다. |
| 제거하시겠습니까?(객체 키) | 이 키에 대한 매핑이 있는 경우 이 맵에서 제거합니다. |
| 크기() | 이 ID 해시 맵의 키-값 매핑 수를 반환합니다. |
| 값() | 이 맵에 포함된 값의 컬렉션 뷰를 반환합니다. |
java.util.AbstractMap 클래스에 선언된 메소드
방법 | 설명 |
|---|---|
| toString() | 이 지도의 문자열 표현을 반환합니다. |
인터페이스 java.util.Map에 선언된 메소드
방법 | 설명 |
|---|---|
| 계산?(K 키 BiFunction super K?? super V?? extends V>리매핑함수) | 지정된 키와 현재 매핑된 값(또는 현재 매핑이 없는 경우 null)에 대한 매핑을 계산하려고 시도합니다. |
| 계산IfAbsent?(K 키 기능 super K?? extends V>매핑함수) | 지정된 키가 아직 값과 연결되지 않은 경우(또는 null에 매핑된 경우) 지정된 매핑 함수를 사용하여 해당 값을 계산하려고 시도하고 null이 아닌 한 이 맵에 입력합니다. |
| 계산IfPresent?(K 키 BiFunction super K?? super V?? extends V>리매핑함수) | 지정된 키의 값이 존재하고 null이 아닌 경우 해당 키와 현재 매핑된 값이 주어지면 새 매핑을 계산하려고 시도합니다. |
| forEach?(BiConsumer super K?? super V>행동) | 모든 항목이 처리되거나 작업에서 예외가 발생할 때까지 이 맵의 각 항목에 대해 지정된 작업을 수행합니다. |
| getOrDefault?(객체 키 V defaultValue) | 지정된 키가 매핑된 값을 반환하거나, 이 맵에 키에 대한 매핑이 포함되어 있지 않은 경우 defaultValue를 반환합니다. |
| 병합?(K 키 V 값 BiFunction super V?? super V?? extends V>리매핑함수) | 지정된 키가 아직 값과 연결되어 있지 않거나 null과 연결되어 있는 경우 해당 키를 지정된 null이 아닌 값과 연결합니다. |
| putIfAbsent?(K 키 V 값) | 지정된 키가 아직 값과 연결되어 있지 않은 경우(또는 null에 매핑된 경우) 해당 키를 지정된 값과 연결하고 null을 반환하고 그렇지 않으면 현재 값을 반환합니다. |
| 제거?(개체 키 개체 값) | 현재 지정된 값에 매핑된 경우에만 지정된 키에 대한 항목을 제거합니다. |
| 교체하시겠습니까?(K 키 V 값) | 현재 일부 값에 매핑된 경우에만 지정된 키에 대한 항목을 바꿉니다. |
| 교체하시겠습니까?(K 키 V oldValue V newValue) | 현재 지정된 값에 매핑된 경우에만 지정된 키에 대한 항목을 바꿉니다. |
| 모두 교체하시겠습니까?(이중 함수 super K?? super V?? extends V>기능) | 모든 항목이 처리되거나 함수에서 예외가 발생할 때까지 각 항목의 값을 해당 항목에 대해 지정된 함수를 호출한 결과로 바꿉니다. |
IdentityHashMap과 비교 해시맵
아래 프로그램은 IdentityHashMap과 HashMap 구현의 차이점을 보여줍니다.
Java// Java code to demonstrate IdentityHashMap and // illustration of how it is different from HashMap import java.util.Map; import java.util.HashMap; import java.util.IdentityHashMap; public class IdentityHashMapExample { public static void main(String[] args) { // Creating HashMap and IdentityHashMap objects Map<String String> hm = new HashMap<>(); Map<String String> ihm = new IdentityHashMap<>(); // Putting key and value in HashMap and IdentityHashMap Object hm.put('hmkey''hmvalue'); hm.put(new String('hmkey')'hmvalue1'); ihm.put('ihmkey''ihmvalue'); ihm.put(new String('ihmkey')'ihmvalue1'); // Print Size of HashMap and WeakHashMap Object // hm.size() will print 1 since it compares the objects logically // and both the keys are same System.out.println('Size of HashMap is : '+hm.size()); // ihm.size() will print 2 since it compares the objects by reference System.out.println('Size of IdentityHashMap is : '+ihm.size()); } }
산출
Size of HashMap is : 1 Size of IdentityHashMap is : 2
IdentityHashMap은 Map 인터페이스를 구현하고 참조 동일성을 사용하여 키를 비교하는 Java 클래스입니다. 일반 HashMap과 비슷하지만 == 연산자를 사용하여 키를 비교하는 대신 == 메서드를 사용합니다. 이는 내용은 동일하지만 객체 참조가 다른 두 개의 키가 IdentityHashMap에서 별개의 키로 처리된다는 것을 의미합니다.
다음은 Java에서 IdentityHashMap을 사용하는 방법에 대한 예입니다.
Java
import java.util.IdentityHashMap; public class IdentityHashMapExample { public static void main(String[] args) { IdentityHashMap<String Integer> map = new IdentityHashMap<>(); // Add key-value pairs to the map String key1 = new String('key'); String key2 = new String('key'); map.put(key1 1); map.put(key2 2); // Get values from the map using the same and different keys System.out.println(map.get(key1)); // Output: 1 System.out.println(map.get(key2)); // Output: 2 System.out.println(map.get(new String('key'))); // Output: null } }
산출
1 2 null
이 예에서는 문자열 키를 정수 값에 매핑하는 IdentityHashMap을 만듭니다. 동일한 내용을 가진 두 개의 서로 다른 String 개체를 사용하여 두 개의 키-값 쌍을 맵에 추가합니다. 그런 다음 동일하고 다른 String 객체를 사용하여 맵에서 값을 검색합니다. 동일한 내용을 가진 두 개의 서로 다른 키를 사용하여 맵에서 값을 검색할 수 있지만 내용은 동일하지만 다른 객체 참조인 String 객체를 사용하여 값을 검색할 수는 없습니다.
IdentityHashMap은 일반 HashMap과 약간 다른 동작을 가지며 일반적으로 참조 동일성이 중요한 특정 상황에서만 유용합니다. 대부분의 경우 일반 HashMap이면 충분하고 더 적합합니다.
e-r 모델 다이어그램
퀴즈 만들기