类java.util.IdentityHashMap源码实例Demo

下面列出了怎么用java.util.IdentityHashMap的API类实例代码及写法,或者点击链接到github查看源代码。

private static <T> Collection<Object[]> makeMapsMoreTypes(String desc,
                                                          T[] keys,
                                                          T val) {
    Collection<Object[]> cases = new ArrayList<>();
    cases.add(createCase("Hashtable with " + desc,
                         new Hashtable<>(), keys, val));
    cases.add(createCase("IdentityHashMap with " + desc,
                         new IdentityHashMap<>(), keys, val));
    cases.add(createCase("TreeMap with " + desc,
                         new TreeMap<>(), keys, val));
    cases.add(createCase("WeakHashMap with " + desc,
                         new WeakHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentHashMap with " + desc,
                         new ConcurrentHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentSkipListMap with " + desc,
                         new ConcurrentSkipListMap<>(), keys, val));
    return cases;
}
 
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Iterator<Map.Entry<String, String>> entrySetIterator =
        identityHashMap.entrySet().iterator();
    Map.Entry<String, String> entry = entrySetIterator.next();

    entrySetIterator.remove();

    try {
        entry.getKey();
        throw new RuntimeException("Test FAILED: Entry not invalidated by removal.");
    } catch (Exception e) { }
}
 
源代码3 项目: vespa   文件: ListMapTestCase.java
@Test
public void testAnotherImplementation() {
    ListMap<String, String> stringMap = new ListMap<>(IdentityHashMap.class);
    String foo = "foo";
    String bar = "bar";
    String far = "far";
    String rab = "rab";

    stringMap.put(foo, bar);
    stringMap.put(foo, far);
    stringMap.put(bar, rab);

    List<String> fooValues = stringMap.get(new String("foo"));
    assertEquals(0, fooValues.size());
    fooValues = stringMap.get(foo);
    assertEquals(2, fooValues.size());
    assertEquals("bar", fooValues.get(0));
    assertEquals("far", fooValues.get(1));


    List<String> barValues = stringMap.get(new String("bar"));
    assertEquals(0, barValues.size());
    barValues = stringMap.get(bar);
    assertEquals(1, barValues.size());
    assertEquals("rab", barValues.get(0));
}
 
源代码4 项目: openjdk-jdk8u   文件: DistinctEntrySetElements.java
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = identityHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    // NB: These comparisons are valid in this case because none of the
    //     keys put into 'identityHashMap' above are equal to any other.
    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
源代码5 项目: avro-util   文件: AvroSchemaUtil.java
private static void traverseSchema(Schema schema, SchemaVisitor visitor, IdentityHashMap<Object, Boolean> visited) {
  if (visited.put(schema, Boolean.TRUE) != null) {
    return; //been there, done that
  }
  visitor.visitSchema(schema);
  switch (schema.getType()) {
    case UNION:
      for (Schema unionBranch : schema.getTypes()) {
        traverseSchema(unionBranch, visitor, visited);
      }
      return;
    case ARRAY:
      traverseSchema(schema.getElementType(), visitor, visited);
      return;
    case MAP:
      traverseSchema(schema.getValueType(), visitor, visited);
      return;
    case RECORD:
      for (Schema.Field field : schema.getFields()) {
        visitor.visitField(field);
        traverseSchema(field.schema(), visitor, visited);
      }
      break;
    default:
  }
}
 
源代码6 项目: pcgen   文件: BonusManager.java
private Map<BonusObj, Object> getTempBonuses()
{
	Map<BonusObj, Object> map = new IdentityHashMap<>();
	getFilteredTempBonusList().forEach((bonus, value) -> {
		pc.setApplied(bonus, false);

		Object source = value.source;
		CDOMObject cdomsource = (source instanceof CDOMObject) ? (CDOMObject) source : null;
		if (bonus.qualifies(pc, cdomsource))
		{
			pc.setApplied(bonus, true);
		}

		if (pc.isApplied(bonus))
		{
			map.put(bonus, source);
		}
	});
	return map;
}
 
源代码7 项目: syncer   文件: SyncDeserializer.java
public static EventDeserializer defaultDeserializer() {
  Map<Long, TableMapEventData> tableMapEventByTableId = new HashMap<>();
  Map<EventType, EventDataDeserializer> eventDataDeserializers = new IdentityHashMap<>();
  eventDataDeserializers.put(EventType.WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.EXT_WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.QUERY, new QueryEventDataDeserializer());
  eventDataDeserializers.put(EventType.TABLE_MAP, new TableMapEventDataDeserializer());

  return new EventDeserializer(new EventHeaderV4Deserializer(), new NullEventDataDeserializer(),
      eventDataDeserializers, tableMapEventByTableId);
}
 
源代码8 项目: vespa   文件: SpanTree.java
private static IdentityHashMap<SpanNode, Integer> getSpanNodes(SpanTree otherToCopy) {
    IdentityHashMap<SpanNode, Integer> map = new IdentityHashMap<SpanNode, Integer>();
    int spanNodeCounter = 0;
    map.put(otherToCopy.getRoot(), spanNodeCounter++);
    Iterator<SpanNode> it = otherToCopy.getRoot().childIteratorRecursive();
    while (it.hasNext()) {
        map.put(it.next(), spanNodeCounter++);
    }
    return map;
}
 
源代码9 项目: j2objc   文件: RetainedWithTest.java
public void testMapChildren() {
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new IdentityHashMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new WeakHashMap<>();
    }
  });
  new MapTest<Color>().run(new MapFactory<Color>(Color.RED) {
    public Map<Color, ValueType> newMap() {
      return new EnumMap<>(Color.class);
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new HashMap<>();
    }
  });
  new MapTest<Integer>().run(new MapFactory<Integer>(5) {
    public Map<Integer, ValueType> newMap() {
      return new TreeMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new Hashtable<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new ConcurrentHashMap<>();
    }
  });
}
 
源代码10 项目: Telegram-FOSS   文件: MergingMediaPeriod.java
public MergingMediaPeriod(CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    MediaPeriod... periods) {
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.periods = periods;
  childrenPendingPreparation = new ArrayList<>();
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamPeriodIndices = new IdentityHashMap<>();
}
 
源代码11 项目: openjdk-jdk8u-backup   文件: Capacity.java
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
源代码12 项目: gemfirexd-oss   文件: OffHeapValidationJUnitTest.java
private void putIdentityHashMap(Region<Object, Object> region, List<ExpectedValues> expected) {
  String key = "keyIdentityHashMap";
  IdentityHashMap<Object,Object> value = new IdentityHashMap<Object,Object>();
  value.put("1", "string 1");
  value.put("2", "string 2");
  region.put(key, value);
  expected.add(new ExpectedValues(value, 40, "java.util.IdentityHashMap", -1, getMemoryAddress(region, key), 1, 0, false, true));
}
 
源代码13 项目: NewsMe   文件: GetBuilder.java
@Override
public GetBuilder addParams(String key, String val)
{
    if (this.params == null)
    {
        params = new IdentityHashMap<>();
    }
    params.put(key, val);
    return this;
}
 
@Test
public void createMetrics() {
  Map<Object, Object> instances = new IdentityHashMap<>();
  instances.put(metrics_listen1_server1, null);
  instances.put(metrics_listen1_server2, null);
  instances.put(metrics_listen2_server1, null);
  instances.put(metrics_listen2_server2, null);
  Assert.assertEquals(4, instances.size());

  Assert.assertSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen1_server2.getEndpointMetric());
  Assert.assertNotSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen2_server1.getEndpointMetric());
  Assert.assertSame(metrics_listen2_server1.getEndpointMetric(), metrics_listen2_server2.getEndpointMetric());
}
 
源代码15 项目: lucene-solr   文件: PerFieldDocValuesFormat.java
@Override
public void merge(MergeState mergeState) throws IOException {
  Map<DocValuesConsumer, Collection<String>> consumersToField = new IdentityHashMap<>();

  // Group each consumer by the fields it handles
  for (FieldInfo fi : mergeState.mergeFieldInfos) {
    if (fi.getDocValuesType() == DocValuesType.NONE) {
      continue;
    }
    // merge should ignore current format for the fields being merged
    DocValuesConsumer consumer = getInstance(fi, true);
    Collection<String> fieldsForConsumer = consumersToField.get(consumer);
    if (fieldsForConsumer == null) {
      fieldsForConsumer = new ArrayList<>();
      consumersToField.put(consumer, fieldsForConsumer);
    }
    fieldsForConsumer.add(fi.name);
  }

  // Delegate the merge to the appropriate consumer
  PerFieldMergeState pfMergeState = new PerFieldMergeState(mergeState);
  try {
    for (Map.Entry<DocValuesConsumer, Collection<String>> e : consumersToField.entrySet()) {
      e.getKey().merge(pfMergeState.apply(e.getValue()));
    }
  } finally {
    pfMergeState.reset();
  }
}
 
源代码16 项目: pcgen   文件: TotalSkillRankFacet.java
private Map<Skill, Double> getConstructingInfo(CharID id)
{
	Map<Skill, Double> map = getInfo(id);
	if (map == null)
	{
		map = new IdentityHashMap<>();
		setCache(id, map);
	}
	return map;
}
 
源代码17 项目: liblevenshtein-java   文件: ProtobufSerializer.java
/**
 * Returns the dictionary of the prototype.
 * @param proto Prototype of the dictionary.
 * @return Dictionary of the prototype.
 */
protected SortedDawg modelOf(final LibLevenshteinProtos.Dawg proto) {
  final Map<LibLevenshteinProtos.DawgNode, DawgNode> nodes =
    new IdentityHashMap<>();
  final DawgNode root = modelOf(proto.getRoot(), nodes);
  return new SortedDawg(proto.getSize(), root);
}
 
源代码18 项目: Telegram   文件: HlsMediaPeriod.java
/**
 * Creates an HLS media period.
 *
 * @param extractorFactory An {@link HlsExtractorFactory} for {@link Extractor}s for the segments.
 * @param playlistTracker A tracker for HLS playlists.
 * @param dataSourceFactory An {@link HlsDataSourceFactory} for {@link DataSource}s for segments
 *     and keys.
 * @param mediaTransferListener The transfer listener to inform of any media data transfers. May
 *     be null if no listener is available.
 * @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
 * @param eventDispatcher A dispatcher to notify of events.
 * @param allocator An {@link Allocator} from which to obtain media buffer allocations.
 * @param compositeSequenceableLoaderFactory A factory to create composite {@link
 *     SequenceableLoader}s for when this media source loads data from multiple streams.
 * @param allowChunklessPreparation Whether chunkless preparation is allowed.
 * @param useSessionKeys Whether to use #EXT-X-SESSION-KEY tags.
 */
public HlsMediaPeriod(
    HlsExtractorFactory extractorFactory,
    HlsPlaylistTracker playlistTracker,
    HlsDataSourceFactory dataSourceFactory,
    @Nullable TransferListener mediaTransferListener,
    LoadErrorHandlingPolicy loadErrorHandlingPolicy,
    EventDispatcher eventDispatcher,
    Allocator allocator,
    CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    boolean allowChunklessPreparation,
    @HlsMetadataType int metadataType,
    boolean useSessionKeys) {
  this.extractorFactory = extractorFactory;
  this.playlistTracker = playlistTracker;
  this.dataSourceFactory = dataSourceFactory;
  this.mediaTransferListener = mediaTransferListener;
  this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
  this.eventDispatcher = eventDispatcher;
  this.allocator = allocator;
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.allowChunklessPreparation = allowChunklessPreparation;
  this.metadataType = metadataType;
  this.useSessionKeys = useSessionKeys;
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamWrapperIndices = new IdentityHashMap<>();
  timestampAdjusterProvider = new TimestampAdjusterProvider();
  sampleStreamWrappers = new HlsSampleStreamWrapper[0];
  enabledSampleStreamWrappers = new HlsSampleStreamWrapper[0];
  manifestUrlIndicesPerWrapper = new int[0][];
  eventDispatcher.mediaPeriodCreated();
}
 
源代码19 项目: treelayout   文件: TreeLayout.java
/**
 * Creates a TreeLayout for a given tree.
 * <p>
 * In addition to the tree the {@link NodeExtentProvider} and the
 * {@link Configuration} must be given.
 * 
    * @param tree &nbsp;
    * @param nodeExtentProvider &nbsp;
    * @param configuration &nbsp;
    * @param useIdentity
 *            [default: false] when true, identity ("==") is used instead of
 *            equality ("equals(...)") when checking nodes. Within a tree
 *            each node must only exist once (using this check).
 */
public TreeLayout(TreeForTreeLayout<TreeNode> tree,
		NodeExtentProvider<TreeNode> nodeExtentProvider,
		Configuration<TreeNode> configuration, boolean useIdentity) {
	this.tree = tree;
	this.nodeExtentProvider = nodeExtentProvider;
	this.configuration = configuration;
	this.useIdentity = useIdentity;

	if (this.useIdentity) {
		this.mod = new IdentityHashMap<TreeNode, Double>();
		this.thread = new IdentityHashMap<TreeNode, TreeNode>();
		this.prelim = new IdentityHashMap<TreeNode, Double>();
		this.change = new IdentityHashMap<TreeNode, Double>();
		this.shift = new IdentityHashMap<TreeNode, Double>();
		this.ancestor = new IdentityHashMap<TreeNode, TreeNode>();
		this.number = new IdentityHashMap<TreeNode, Integer>();
		this.positions = new IdentityHashMap<TreeNode, Point2D>();
	} else {
		this.mod = new HashMap<TreeNode, Double>();
		this.thread = new HashMap<TreeNode, TreeNode>();
		this.prelim = new HashMap<TreeNode, Double>();
		this.change = new HashMap<TreeNode, Double>();
		this.shift = new HashMap<TreeNode, Double>();
		this.ancestor = new HashMap<TreeNode, TreeNode>();
		this.number = new HashMap<TreeNode, Integer>();
		this.positions = new HashMap<TreeNode, Point2D>();
	}
	
	// No need to explicitly set mod, thread and ancestor as their getters
	// are taking care of the initial values. This avoids a full tree walk
	// through and saves some memory as no entries are added for
	// "initial values".

	TreeNode r = tree.getRoot();
	firstWalk(r, null);
	calcSizeOfLevels(r, 0);
	secondWalk(r, -getPrelim(r), 0, 0);
}
 
源代码20 项目: netbeans   文件: ClusteredIndexablesCacheTest.java
private void globalPathRegistry_register(String id, ClassPath [] classpaths) {
    Map<ClassPath,Void> map = registeredClasspaths.get(id);
    if (map == null) {
        map = new IdentityHashMap<ClassPath, Void>();
        registeredClasspaths.put(id, map);
    }
    for (ClassPath cp :  classpaths) {
        map.put(cp,null);
    }
    GlobalPathRegistry.getDefault().register(id, classpaths);
}
 
源代码21 项目: pcgen   文件: BonusManager.java
private Map<BonusObj, Object> getAllActiveBonuses()
{
	Map<BonusObj, Object> ret = new IdentityHashMap<>();
	for (final BonusContainer pobj : pc.getBonusContainerList())
	{
		// We exclude equipmods here as their bonuses are already counted in
		// the equipment they belong to.
		if (pobj != null && !(pobj instanceof EquipmentModifier))
		{
			boolean use = true;
			if (pobj instanceof PCClass)
			{
				// Class bonuses are only included if the level is greater
				// than 0
				// This is because 0 levels of a class can be added to
				// access spell casting etc
				use = pc.getLevel(((PCClass) pobj)) > 0;
			}
			if (use)
			{
				pobj.activateBonuses(pc);
				List<BonusObj> abs = pobj.getActiveBonuses(pc);
				for (BonusObj bo : abs)
				{
					ret.put(bo, pobj);
				}
			}
		}
	}

	if (pc.getUseTempMods())
	{
		ret.putAll(getTempBonuses());
	}
	return ret;
}
 
源代码22 项目: astor   文件: EdgesBuilder.java
/** Simple constructor.
 * @param root tree root
 * @param tolerance below which points are consider to be identical
 */
public EdgesBuilder(final BSPTree<Sphere2D> root, final double tolerance) {
    this.root            = root;
    this.tolerance       = tolerance;
    this.edgeToNode      = new IdentityHashMap<Edge, BSPTree<Sphere2D>>();
    this.nodeToEdgesList = new IdentityHashMap<BSPTree<Sphere2D>, List<Edge>>();
}
 
源代码23 项目: dragonwell8_jdk   文件: Capacity.java
static int capacity(IdentityHashMap<?,?> map) {
    try {
        return ((Object[]) tableField.get(map)).length / 2;
    } catch (Throwable t) {
        throw new LinkageError("table", t);
    }
}
 
源代码24 项目: pcgen   文件: BonusManager.java
private Map<BonusObj, TempBonusInfo> getFilteredTempBonusList()
{
	final Map<BonusObj, TempBonusInfo> ret = new IdentityHashMap<>();
	for (Map.Entry<BonusObj, TempBonusInfo> me : tempBonusBySource.entrySet())
	{
		BonusObj bonus = me.getKey();
		TempBonusInfo ti = me.getValue();
		if (!tempBonusFilters.contains(BonusDisplay.getBonusDisplayName(ti)))
		{
			ret.put(bonus, ti);
		}
	}
	return ret;
}
 
源代码25 项目: NewsMe   文件: PostFormBuilder.java
@Override
public PostFormBuilder addHeader(String key, String val)
{
    if (this.headers == null)
    {
        headers = new IdentityHashMap<>();
    }
    headers.put(key, val);
    return this;
}
 
源代码26 项目: Telegram-FOSS   文件: HlsMediaPeriod.java
/**
 * Creates an HLS media period.
 *
 * @param extractorFactory An {@link HlsExtractorFactory} for {@link Extractor}s for the segments.
 * @param playlistTracker A tracker for HLS playlists.
 * @param dataSourceFactory An {@link HlsDataSourceFactory} for {@link DataSource}s for segments
 *     and keys.
 * @param mediaTransferListener The transfer listener to inform of any media data transfers. May
 *     be null if no listener is available.
 * @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
 * @param eventDispatcher A dispatcher to notify of events.
 * @param allocator An {@link Allocator} from which to obtain media buffer allocations.
 * @param compositeSequenceableLoaderFactory A factory to create composite {@link
 *     SequenceableLoader}s for when this media source loads data from multiple streams.
 * @param allowChunklessPreparation Whether chunkless preparation is allowed.
 * @param useSessionKeys Whether to use #EXT-X-SESSION-KEY tags.
 */
public HlsMediaPeriod(
    HlsExtractorFactory extractorFactory,
    HlsPlaylistTracker playlistTracker,
    HlsDataSourceFactory dataSourceFactory,
    @Nullable TransferListener mediaTransferListener,
    LoadErrorHandlingPolicy loadErrorHandlingPolicy,
    EventDispatcher eventDispatcher,
    Allocator allocator,
    CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    boolean allowChunklessPreparation,
    @HlsMetadataType int metadataType,
    boolean useSessionKeys) {
  this.extractorFactory = extractorFactory;
  this.playlistTracker = playlistTracker;
  this.dataSourceFactory = dataSourceFactory;
  this.mediaTransferListener = mediaTransferListener;
  this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
  this.eventDispatcher = eventDispatcher;
  this.allocator = allocator;
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.allowChunklessPreparation = allowChunklessPreparation;
  this.metadataType = metadataType;
  this.useSessionKeys = useSessionKeys;
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamWrapperIndices = new IdentityHashMap<>();
  timestampAdjusterProvider = new TimestampAdjusterProvider();
  sampleStreamWrappers = new HlsSampleStreamWrapper[0];
  enabledSampleStreamWrappers = new HlsSampleStreamWrapper[0];
  manifestUrlIndicesPerWrapper = new int[0][];
  eventDispatcher.mediaPeriodCreated();
}
 
源代码27 项目: gadtry   文件: OffHeapMapTest.java
@Test
public void putAllTest()
{
    final Map<String, Integer> offHeapMap = new OffHeapMap<>(
            (Integer str) -> String.valueOf(str).getBytes(UTF_8),
            (byte[] bytes) -> Integer.valueOf(new String(bytes, UTF_8)),
            IdentityHashMap::new
    );
    Map<String, Integer> integerMap = MutableMap.of("a1", 123);
    offHeapMap.putAll(integerMap);

    Assert.assertEquals(offHeapMap, integerMap);
}
 
源代码28 项目: jdk8u-jdk   文件: Capacity.java
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
源代码29 项目: kodkod   文件: Translator.java
/**
 * Returns an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.  The annotated formula f will contain transitive source 
 * information for each of the subformulas of f.node.  Specifically, let t be a subformula of f.node, and
 * s be a descdendent of annotated.node from which t was derived.  Then, f.source[t] = annotated.source[s]. </p>
 * @requires simplified.keySet() in annotated.predicates()[RelationPredicate.NAME]
 * @requires no disj p, p': simplified.keySet() | simplified.get(p) = simplified.get(p') // this must hold in order
 * to maintain the invariant that each subformula of the returned formula has exactly one source
 * @requires for each p in simplified.keySet(), the formulas "p and [[this.bounds]]" and
 * "simplified.get(p) and [[this.bounds]]" are equisatisfiable
 * @return an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.
 */
private AnnotatedNode<Formula> inlinePredicates(final AnnotatedNode<Formula> annotated, final Map<RelationPredicate,Formula> simplified) {
	final Map<Node,Node> sources = new IdentityHashMap<Node,Node>();
	final AbstractReplacer inliner = new AbstractReplacer(annotated.sharedNodes()) {
		private RelationPredicate source =  null;			
		protected <N extends Node> N cache(N node, N replacement) {
			if (replacement instanceof Formula) {
				if (source==null) {
					final Node nsource = annotated.sourceOf(node);
					if (replacement!=nsource) 
						sources.put(replacement, nsource);
				} else {
					sources.put(replacement, source);
				}
			}
			return super.cache(node, replacement);
		}
		public Formula visit(RelationPredicate pred) {
			Formula ret = lookup(pred);
			if (ret!=null) return ret;
			source = pred;
			if (simplified.containsKey(pred)) {
				ret = simplified.get(pred).accept(this);
			} else {
				ret = pred.toConstraints().accept(this);
			}
			source = null;
			return cache(pred, ret);
		}
	};

	return annotate(annotated.node().accept(inliner), sources);
}
 
/**
 * Constructor for ASTRewriteAnalyzer.
 * <p>The given options cannot be null.</p>
 * 
 * @param content the content of the compilation unit to rewrite.
 * @param lineInfo line information for the content of the compilation unit to rewrite.
 * @param rootEdit the edit to add all generated edits to
 * @param eventStore the event store containing the description of changes
 * @param nodeInfos annotations to nodes, such as if a node is a string placeholder or a copy target
 * @param comments list of comments of the compilation unit to rewrite (elements of type <code>Comment</code>) or <code>null</code>.
 * @param options the current jdt.core options (formatting/compliance)
 * @param extendedSourceRangeComputer the source range computer to use
 * @param recoveryScannerData internal data used by {@link RecoveryScanner}
 */
public ASTRewriteAnalyzer(
		char[] content,
		LineInformation lineInfo,
		String lineDelim,
		TextEdit rootEdit,
		RewriteEventStore eventStore,
		NodeInfoStore nodeInfos,
		List comments,
		Map options,
		TargetSourceRangeComputer extendedSourceRangeComputer,
		RecoveryScannerData recoveryScannerData) {
	this.eventStore= eventStore;
	this.content= content;
	this.lineInfo= lineInfo;
	this.nodeInfos= nodeInfos;
	this.tokenScanner= null;
	this.currentEdit= rootEdit;
	this.sourceCopyInfoToEdit= new IdentityHashMap();
	this.sourceCopyEndNodes= new Stack();

	this.formatter= new ASTRewriteFormatter(nodeInfos, eventStore, options, lineDelim);

	this.extendedSourceRangeComputer = extendedSourceRangeComputer;
	this.lineCommentEndOffsets= new LineCommentEndOffsets(comments);
	
	this.options = options;
	
	this.recoveryScannerData = recoveryScannerData;
}
 
 类所在包
 同包方法