java.util.IdentityHashMap类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(152)

本文整理了Java中java.util.IdentityHashMap类的一些代码示例,展示了IdentityHashMap类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。IdentityHashMap类的具体详情如下:
包路径:java.util.IdentityHashMap
类名称:IdentityHashMap

IdentityHashMap介绍

[英]This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.

This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This class provides constant-time performance for the basic operations (get and put), assuming the system identity hash function ( System#identityHashCode(Object)) disperses elements properly among the buckets.

This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified.

If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage.

Note that this implementation is not synchronized. If multiple threads access an identity hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections#synchronizedMapmethod. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new IdentityHashMap(...));

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: fail-fast iterators should be used only to detect bugs.

Implementation note: This is a simple linear-probe hash table, as described for example in texts by Sedgewick and Knuth. The array alternates holding keys and values. (This has better locality for large tables than does using separate arrays.) For many JRE implementations and operation mixes, this class will yield better performance than HashMap (which uses chaining rather than linear-probing).

This class is a member of the Java Collections Framework.
[中]此类使用哈希表实现映射接口,在比较键(和值)时使用引用相等代替对象相等。换句话说,在IdentityHashMap中,两个键k1和k2被认为是相等的当且仅当(k1==k2)。(在普通映射实现中(如HashMap),两个键k1和k2被认为是相等的当且仅当(k1==null?k2==null:k1.equals(k2)))
此类不是通用的映射实现!虽然该类实现了Map接口,但它故意违反了Map的一般约定,该约定要求在比较对象时使用equals方法。此类仅设计用于少数需要引用相等语义的情况。
此类的典型用途是拓扑保持对象图转换,例如序列化或深度复制。要执行这样的转换,程序必须维护一个“节点表”,该表跟踪已处理的所有对象引用。节点表不能使不同的对象相等,即使它们恰好相等。此类的另一个典型用途是维护代理对象。例如,调试工具可能希望为正在调试的程序中的每个对象维护一个代理对象。
此类提供所有可选的映射操作,并允许空值和空键。此类不保证地图的顺序;特别是,它不能保证订单在一段时间内保持不变。
假定系统标识散列函数(system#identityHashCode(Object))将元素正确地分散在存储桶之间,则此类为基本操作(get和put)提供恒定时间性能。
此类有一个调优参数(影响性能但不影响语义):预期最大大小。此参数是该映射应包含的最大键值映射数。在内部,此参数用于确定最初包含哈希表的存储桶数。预期最大尺寸和铲斗数量之间的精确关系尚未确定。
如果映射的大小(键值映射的数量)充分超过预期的最大大小,则桶的数量会增加。增加桶的数量(“重新灰化”)可能会相当昂贵,因此创建具有足够大的预期最大大小的标识哈希映射是值得的。另一方面,集合视图上的迭代需要与哈希表中的桶数成比例的时间,因此,如果您特别关心迭代性能或内存使用情况,则不必将预期的最大大小设置得太高。
请注意,此实现是不同步的。如果多个线程同时访问标识哈希映射,并且至少有一个线程在结构上修改映射,则必须在外部对其进行同步。(结构修改是添加或删除一个或多个映射的任何操作;仅更改与实例已包含的键关联的值不是结构修改。)这通常是通过在自然封装贴图的某个对象上进行同步来实现的。如果不存在此类对象,则应使用Collections#SynchronizedMap方法“包装”映射。最好在创建时执行此操作,以防止意外不同步地访问映射:

Map m = Collections.synchronizedMap(new IdentityHashMap(...));

这个类的所有“集合视图方法”返回的集合的迭代器方法返回的迭代器都是快速失效的:如果在迭代器创建后的任何时候,以迭代器自己的remove方法以外的任何方式对映射进行结构修改,迭代器将抛出ConcurrentModificationException。因此,在面对并发修改时,迭代器会快速、干净地失败,而不是在将来的不确定时间冒着任意、不确定行为的风险。
请注意,无法保证迭代器的快速失效行为,因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬保证。快速失败迭代器会尽最大努力抛出ConcurrentModificationException。因此,编写依赖于此异常的正确性的程序是错误的:fail fast迭代器应该只用于检测bug。
实现说明:这是一个简单的线性探测哈希表,如Sedgewick和Knuth在文本中所述。数组交替保存键和值。(对于大型表,这比使用单独的数组具有更好的局部性。)对于许多JRE实现和操作混合,该类将产生比HashMap(使用链接而不是线性探测)更好的性能。
此类是Java Collections Framework的成员。

代码示例

代码示例来源:origin: google/guava

/**
 * Creates an {@code IdentityHashMap} instance.
 *
 * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
 * deprecated. Instead, use the {@code IdentityHashMap} constructor directly, taking advantage of
 * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
 *
 * @return a new, empty {@code IdentityHashMap}
 */
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
 return new IdentityHashMap<>();
}

代码示例来源:origin: apache/incubator-druid

private WritableMemory getMemory(ByteBuffer buffer)
{
 WritableMemory mem = memCache.get(buffer);
 if (mem == null) {
  mem = WritableMemory.wrap(buffer, ByteOrder.LITTLE_ENDIAN);
  memCache.put(buffer, mem);
 }
 return mem;
}

代码示例来源:origin: apache/incubator-dubbo

private static JavaBeanDescriptor createDescriptorIfAbsent(Object obj, JavaBeanAccessor accessor, IdentityHashMap<Object, JavaBeanDescriptor> cache) {
  if (cache.containsKey(obj)) {
    return cache.get(obj);
  } else if (obj instanceof JavaBeanDescriptor) {
    return (JavaBeanDescriptor) obj;
  } else {
    JavaBeanDescriptor result = createDescriptorForSerialize(obj.getClass());
    cache.put(obj, result);
    serializeInternal(result, obj, accessor, cache);
    return result;
  }
}

代码示例来源:origin: apache/incubator-dubbo

/**
 * Replaces a reference from one object to another.
 */
@Override
public boolean replaceRef(Object oldRef, Object newRef)
    throws IOException {
  Integer value = (Integer) _refs.remove(oldRef);
  if (value != null) {
    _refs.put(newRef, value);
    return true;
  } else
    return false;
}

代码示例来源:origin: SonarSource/sonarqube

void match(RAW raw, BASE base) {
 if (!rawToBase.containsKey(raw)) {
  rawToBase.put(raw, base);
  baseToRaw.put(base, raw);
 }
}

代码示例来源:origin: spring-projects/spring-framework

private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, ?> beans) {
  IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>();
  beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName));
  return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
}

代码示例来源:origin: apache/incubator-dubbo

/**
 * If the object has already been written, just write its ref.
 *
 * @return true if we're writing a ref.
 */
@Override
public boolean addRef(Object object)
    throws IOException {
  if (_refs == null)
    _refs = new IdentityHashMap();
  Integer ref = (Integer) _refs.get(object);
  if (ref != null) {
    int value = ref.intValue();
    writeRef(value);
    return true;
  } else {
    _refs.put(object, new Integer(_refs.size()));
    return false;
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

static IdentityHashMap<Tree, List<Tree>> getTopParses(LexicalizedParser parser, Options op,
                           Collection<Tree> trees, TreeTransformer transformer,
                           boolean outputUpdates) {
 IdentityHashMap<Tree, List<Tree>> topParses = new IdentityHashMap<>();
 for (Tree tree : trees) {
  List<Tree> parses = getTopParsesForOneTree(parser, op.trainOptions.dvKBest, tree, transformer);
  topParses.put(tree, parses);
  if (outputUpdates && topParses.size() % 10 == 0) {
   log.info("Processed " + topParses.size() + " trees");
  }
 }
 if (outputUpdates) {
  log.info("Finished processing " + topParses.size() + " trees");
 }
 return topParses;
}

代码示例来源:origin: junit-team/junit4

/**
 * Sets order value for the specified rule.
 */
public void setOrder(Object rule, int order) {
  orderValues.put(rule, order);
}

代码示例来源:origin: stanfordnlp/CoreNLP

Tree getParent(Tree node) {
 if (node instanceof HasParent) {
  return node.parent();
 }
 if (nodesToParents == null) {
  nodesToParents = new IdentityHashMap<>();
 }
 if (nodesToParents.isEmpty()) {
  fillNodesToParents(root, null);
 }
 return nodesToParents.get(node);
}

代码示例来源:origin: facebook/stetho

public ElementInfo getElementInfo(Object element) {
 // Return ElementInfo for the new (albeit uncommitted and pre-garbage collected) view of the
 // Document. If element is garbage then you'll still get its info (feature, not a bug :)).
 ElementInfo elementInfo = mElementToInfoChangesMap.get(element);
 if (elementInfo != null) {
  return elementInfo;
 }
 return mElementToInfoMap.get(element);
}

代码示例来源:origin: apache/incubator-druid

@Override
public void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer)
{
 createNewUnion(newBuffer, newPosition, true);
 Int2ObjectMap<Union> unionMap = unions.get(oldBuffer);
 if (unionMap != null) {
  unionMap.remove(oldPosition);
  if (unionMap.isEmpty()) {
   unions.remove(oldBuffer);
   memCache.remove(oldBuffer);
  }
 }
}

代码示例来源:origin: stanfordnlp/CoreNLP

public IdentityHashMap<Tree, byte[]> convertToBytes(IdentityHashMap<Tree, List<Tree>> uncompressed) {
 IdentityHashMap<Tree, byte[]> compressed = Generics.newIdentityHashMap();
 for (Map.Entry<Tree, List<Tree>> entry : uncompressed.entrySet()) {
  compressed.put(entry.getKey(), convertToBytes(entry.getValue()));
 }
 return compressed;
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
public void exitMessageRef(MessageRefExpression expr) {
  final Object field = blockOrMissing(codeSnippet.get(expr.getFieldExpr()), expr.getFieldExpr());
  codeSnippet.putIfAbsent(expr, CodeBlock.of("context.currentMessage().getField($S)", field));
}

代码示例来源:origin: stanfordnlp/CoreNLP

/** Returns true if this set contains the specified element.
 *
 *  Remember that this set implementation uses == (not
 *  <code>equals()</code>) to test whether an element is present in the
 *  set.
 *
 *  @param o Element whose presence in this set is to be
 *  tested.
 *
 *  @return <code>true</code> if this set contains the specified element.
 */
@Override
public boolean contains(Object o) {
 return map.containsKey(o);
}

代码示例来源:origin: apache/incubator-dubbo

/**
 * Removes a reference.
 */
@Override
public boolean removeRef(Object obj)
    throws IOException {
  if (_refs != null) {
    _refs.remove(obj);
    return true;
  } else
    return false;
}

代码示例来源:origin: apache/kafka

@Override
public void deallocate(ByteBuffer buffer, int size) {
  if (!allocatedBuffers.containsKey(buffer)) {
    throw new IllegalStateException("Deallocating a buffer that is not allocated");
  }
  allocatedBuffers.remove(buffer);
  super.deallocate(buffer, size);
}

代码示例来源:origin: org.springframework/spring-beans

private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, ?> beans) {
  IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>();
  beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName));
  return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
}

代码示例来源:origin: stanfordnlp/CoreNLP

/** Adds the supplied element to this set.  This private method is used
 *  internally [by clone()] instead of add(), because add() can be
 *  overridden to do unexpected things.
 *
 *  @param    o        the element to add to this set
 */
private void internalAdd(E o) {
 map.put(o, Boolean.TRUE);
}

代码示例来源:origin: Graylog2/graylog2-server

static long sizeForValue(@Nonnull Object value) {
  long valueSize;
  if (value instanceof CharSequence) {
    valueSize = ((CharSequence) value).length();
  } else {
    final Integer classSize = classSizes.get(value.getClass());
    valueSize = classSize == null ? 0 : classSize;
  }
  return valueSize;
}

相关文章