下面列出了java.util.IdentityHashMap#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static CodecRegistry fromAppPojoCodecs(TypeModelMapper typeModelMapper, List<PojoCodecImpl<?>> pojoCodecs) {
final Long2ObjectMap<PojoCodecImpl<?>> typeId2CodecMap = new Long2ObjectOpenHashMap<>(pojoCodecs.size());
final IdentityHashMap<Class<?>, PojoCodecImpl<?>> type2CodecMap = new IdentityHashMap<>(pojoCodecs.size());
for (PojoCodecImpl<?> pojoCodec : pojoCodecs) {
final Class<?> type = pojoCodec.getEncoderClass();
final TypeModel typeModel = typeModelMapper.ofType(type);
if (typeModel == null) {
continue;
}
FastCollectionsUtils.requireNotContains(typeId2CodecMap, typeModel.typeId().toGuid(), "typeId-(toGuid)");
CollectionUtils.requireNotContains(type2CodecMap, type, "type");
typeId2CodecMap.put(typeModel.typeId().toGuid(), pojoCodec);
type2CodecMap.put(type, pojoCodec);
}
return new DefaultCodecRegistry(typeModelMapper, typeId2CodecMap, type2CodecMap);
}
/**
* Helper method that clones an item
*
* @param item the item to clone
* @return a clone of item.
*/
public static Map<String, AttributeValue> cloneItem(final Map<String, AttributeValue> item) {
if (item == null) {
return null;
}
final Map<String, AttributeValue> clonedItem = Maps.newHashMap();
final IdentityHashMap<AttributeValue, AttributeValue> sourceDestinationMap = new IdentityHashMap<>();
for (Entry<String, AttributeValue> entry : item.entrySet()) {
if (!sourceDestinationMap.containsKey(entry.getValue())) {
sourceDestinationMap.put(entry.getValue(), clone(entry.getValue(), sourceDestinationMap));
}
clonedItem.put(entry.getKey(), sourceDestinationMap.get(entry.getValue()));
}
return clonedItem;
}
private void checkLabelCount(Query q, String field, int[] expected) throws IOException {
Weight w = searcher.createWeight(searcher.rewrite(q), ScoreMode.COMPLETE, 1);
for (int i = 0; i < expected.length; i++) {
LeafReaderContext ctx = searcher.leafContexts.get(ReaderUtil.subIndex(i, searcher.leafContexts));
int doc = i - ctx.docBase;
Matches matches = w.matches(ctx, doc);
if (matches == null) {
assertEquals("Expected to get matches on document " + i, 0, expected[i]);
continue;
}
MatchesIterator it = matches.getMatches(field);
if (expected[i] == 0) {
assertNull(it);
continue;
}
else {
assertNotNull(it);
}
IdentityHashMap<Query, Integer> labels = new IdentityHashMap<>();
while (it.next()) {
labels.put(it.getQuery(), 1);
}
assertEquals(expected[i], labels.size());
}
}
private boolean checkChildren(LogicalExpression e, IdentityHashMap<LogicalExpression, Object> value, boolean transmitsConstant){
List<LogicalExpression> constants = Lists.newLinkedList();
boolean constant = true;
for(LogicalExpression child : e){
if(child.accept(this, value)){
constants.add(child);
}else{
constant = false;
}
}
// if one or more clauses isn't constant, this isn't constant. this also isn't a constant if it operates on a set.
if(!constant || !transmitsConstant){
for(LogicalExpression c: constants){
value.put(c, true);
}
}
return constant && transmitsConstant;
}
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.");
}
}
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.");
}
}
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) { }
}
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:
}
}
@SuppressWarnings("unchecked") // $NON-NLS-1$
public static void addEncodeResource(UIViewRootEx rootEx, Resource resource) {
if(ExtLibUtil.isXPages852()) {
// The XPages runtime add all the resources and does a check when it starts to
// generate all the resources at the very end.
// For performance reasons, and until the XPages runtime optimizes this, we ensure
// that the same resource (the exact same object - identity comparison) is not
// added multiple times.
// Already optimized in post 852
IdentityHashMap<Resource, Boolean> m = (IdentityHashMap<Resource, Boolean>)rootEx.getEncodeProperty("extlib.EncodeResource"); // $NON-NLS-1$
if(m==null) {
m = new IdentityHashMap<Resource, Boolean>();
} else {
if(m.containsKey(resource)) {
return;
}
}
m.put(resource, Boolean.TRUE);
}
rootEx.addEncodeResource(resource);
}
/**
* Returns all of the {@link ConfigurationOption} in the specified {@link Addon}.
*/
public static Iterable<ConfigurationOption> getWindupConfigurationOptions(Addon addon)
{
IdentityHashMap<ClassLoader, Addon> classLoaderToAddon = new IdentityHashMap<>();
for (Addon loadedAddon : FurnaceHolder.getAddonRegistry().getAddons())
{
classLoaderToAddon.put(loadedAddon.getClassLoader(), loadedAddon);
}
List<ConfigurationOption> results = new ArrayList<>();
Imported<ConfigurationOption> options = FurnaceHolder.getAddonRegistry()
.getServices(ConfigurationOption.class);
for (ConfigurationOption option : options)
{
ClassLoader optionClassLoader = option.getClass().getClassLoader();
Addon optionAddon = classLoaderToAddon.get(optionClassLoader);
if (optionAddon.equals(addon))
{
results.add(option);
}
}
return results;
}
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) { }
}
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) { }
}
private FactoryAwareOrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, Object> beans) {
IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<Object, String>();
for (Map.Entry<String, Object> entry : beans.entrySet()) {
instancesToBeanNames.put(entry.getValue(), entry.getKey());
}
return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
}
/**
* java.util.IdentityHashMap#Serialization()
*/
public void test_Serialization() throws Exception {
IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
map.put(ID, "world");
// BEGIN Android-added
// Regression test for null key in serialized IdentityHashMap (1178549)
// Together with this change the IdentityHashMap.golden.ser resource
// was replaced by a version that contains a map with a null key.
map.put(null, "null");
// END Android-added
SerializationTest.verifySelf(map, comparator);
SerializationTest.verifyGolden(this, map, comparator);
}
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;
}
}
protected byte[] buildTrieBytes(int baseId) {
checkOverflowParts(this.root);
Stats stats = stats();
int sizeNoValuesBeneath = stats.mbpn_sizeNoValueBeneath;
int sizeChildOffset = stats.mbpn_sizeChildOffset;
if (stats.mbpn_footprint <= 0) // must never happen, but let us be cautious
throw new IllegalStateException("Too big dictionary, dictionary cannot be bigger than 2GB");
if (stats.mbpn_footprint > _2GB)
throw new RuntimeException("Too big dictionary, dictionary cannot be bigger than 2GB");
// write head
byte[] head;
try {
ByteArrayOutputStream byteBuf = new ByteArrayOutputStream();
DataOutputStream headOut = new DataOutputStream(byteBuf);
headOut.write(TrieDictionary.MAGIC);
headOut.writeShort(0); // head size, will back fill
headOut.writeInt((int) stats.mbpn_footprint); // body size
headOut.write(sizeChildOffset);
headOut.write(sizeNoValuesBeneath);
positiveShortPreCheck(baseId, "baseId");
headOut.writeShort(baseId);
positiveShortPreCheck(stats.maxValueLength, "stats.maxValueLength");
headOut.writeShort(stats.maxValueLength);
headOut.writeUTF(bytesConverter == null ? "" : bytesConverter.getClass().getName());
headOut.close();
head = byteBuf.toByteArray();
BytesUtil.writeUnsigned(head.length, head, TrieDictionary.MAGIC_SIZE_I, 2);
} catch (IOException e) {
throw new RuntimeException(e); // shall not happen, as we are writing in memory
}
byte[] trieBytes = new byte[(int) stats.mbpn_footprint + head.length];
System.arraycopy(head, 0, trieBytes, 0, head.length);
LinkedList<Node> open = new LinkedList<Node>();
IdentityHashMap<Node, Integer> offsetMap = new IdentityHashMap<Node, Integer>();
// write body
int o = head.length;
offsetMap.put(root, o);
o = build_writeNode(root, o, true, sizeNoValuesBeneath, sizeChildOffset, trieBytes);
if (root.children.isEmpty() == false)
open.addLast(root);
while (open.isEmpty() == false) {
Node parent = open.removeFirst();
build_overwriteChildOffset(offsetMap.get(parent), o - head.length, sizeChildOffset, trieBytes);
for (int i = 0; i < parent.children.size(); i++) {
Node c = parent.children.get(i);
boolean isLastChild = (i == parent.children.size() - 1);
offsetMap.put(c, o);
o = build_writeNode(c, o, isLastChild, sizeNoValuesBeneath, sizeChildOffset, trieBytes);
if (c.children.isEmpty() == false)
open.addLast(c);
}
}
if (o != trieBytes.length)
throw new RuntimeException();
return trieBytes;
}
static void growUsingPut(IdentityHashMap<Object,Object> map,
int elementsToAdd) {
for (int i = 0; i < elementsToAdd; i++)
map.put(new Object(), new Object());
}
protected byte[] buildTrieBytes(int baseId) {
checkOverflowParts(this.root);
Stats stats = stats();
int sizeNoValuesBeneath = stats.mbpn_sizeNoValueBeneath;
int sizeChildOffset = stats.mbpn_sizeChildOffset;
if (stats.mbpn_footprint <= 0) // must never happen, but let us be cautious
throw new IllegalStateException("Too big dictionary, dictionary cannot be bigger than 2GB");
if (stats.mbpn_footprint > _2GB)
throw new RuntimeException("Too big dictionary, dictionary cannot be bigger than 2GB");
// write head
byte[] head;
try {
ByteArrayOutputStream byteBuf = new ByteArrayOutputStream();
DataOutputStream headOut = new DataOutputStream(byteBuf);
headOut.write(TrieDictionary.MAGIC);
headOut.writeShort(0); // head size, will back fill
headOut.writeInt((int) stats.mbpn_footprint); // body size
headOut.write(sizeChildOffset);
headOut.write(sizeNoValuesBeneath);
positiveShortPreCheck(baseId, "baseId");
headOut.writeShort(baseId);
positiveShortPreCheck(stats.maxValueLength, "stats.maxValueLength");
headOut.writeShort(stats.maxValueLength);
headOut.writeUTF(bytesConverter == null ? "" : bytesConverter.getClass().getName());
headOut.close();
head = byteBuf.toByteArray();
BytesUtil.writeUnsigned(head.length, head, TrieDictionary.MAGIC_SIZE_I, 2);
} catch (IOException e) {
throw new RuntimeException(e); // shall not happen, as we are writing in memory
}
byte[] trieBytes = new byte[(int) stats.mbpn_footprint + head.length];
System.arraycopy(head, 0, trieBytes, 0, head.length);
LinkedList<Node> open = new LinkedList<Node>();
IdentityHashMap<Node, Integer> offsetMap = new IdentityHashMap<Node, Integer>();
// write body
int o = head.length;
offsetMap.put(root, o);
o = build_writeNode(root, o, true, sizeNoValuesBeneath, sizeChildOffset, trieBytes);
if (root.children.isEmpty() == false)
open.addLast(root);
while (open.isEmpty() == false) {
Node parent = open.removeFirst();
build_overwriteChildOffset(offsetMap.get(parent), o - head.length, sizeChildOffset, trieBytes);
for (int i = 0; i < parent.children.size(); i++) {
Node c = parent.children.get(i);
boolean isLastChild = (i == parent.children.size() - 1);
offsetMap.put(c, o);
o = build_writeNode(c, o, isLastChild, sizeNoValuesBeneath, sizeChildOffset, trieBytes);
if (c.children.isEmpty() == false)
open.addLast(c);
}
}
if (o != trieBytes.length)
throw new RuntimeException();
return trieBytes;
}
/**
* Computes a base {@link DocSet} for the current request to be used
* when computing global stats for the local index.
*
* This is typically the same as the main DocSet for the {@link ResponseBuilder}
* unless {@link CommonParams#TAG tag}ged filter queries have been excluded using
* the {@link CommonParams#EXCLUDE ex} local param
*/
public DocSet computeBaseDocSet() throws IOException {
DocSet docs = rb.getResults().docSet;
Map<?,?> tagMap = (Map<?,?>) rb.req.getContext().get("tags");
if (excludeTagList.isEmpty() || null == tagMap) {
// either the exclude list is empty, or there
// aren't any tagged filters to exclude anyway.
return docs;
}
IdentityHashMap<Query,Boolean> excludeSet = new IdentityHashMap<Query,Boolean>();
for (String excludeTag : excludeTagList) {
Object olst = tagMap.get(excludeTag);
// tagMap has entries of List<String,List<QParser>>, but subject to change in the future
if (!(olst instanceof Collection)) continue;
for (Object o : (Collection<?>)olst) {
if (!(o instanceof QParser)) continue;
QParser qp = (QParser)o;
try {
excludeSet.put(qp.getQuery(), Boolean.TRUE);
} catch (SyntaxError e) {
// this shouldn't be possible since the request should have already
// failed when attempting to execute the query, but just in case...
throw new SolrException(ErrorCode.BAD_REQUEST, "Excluded query can't be parsed: " +
originalParam + " due to: " + e.getMessage(), e);
}
}
}
if (excludeSet.size() == 0) return docs;
List<Query> qlist = new ArrayList<Query>();
// add the base query
if (!excludeSet.containsKey(rb.getQuery())) {
qlist.add(rb.getQuery());
}
// add the filters
if (rb.getFilters() != null) {
for (Query q : rb.getFilters()) {
if (!excludeSet.containsKey(q)) {
qlist.add(q);
}
}
}
// get the new base docset for this facet
return searcher.getDocSet(qlist);
}
/**
* @param ctx Reader context.
* @param handles Handles for already traversed objects.
* @return String representation.
*/
private String toString(BinaryReaderHandles ctx, IdentityHashMap<BinaryObject, Integer> handles) {
int idHash = System.identityHashCode(this);
int hash = hashCode();
BinaryType meta;
IgniteThread.onForbidBinaryMetadataRequestSectionEntered();
try {
meta = rawType();
}
catch (BinaryObjectException ignore) {
meta = null;
}
finally {
IgniteThread.onForbidBinaryMetadataRequestSectionLeft();
}
if (meta == null || !S.includeSensitive())
return S.toString(S.includeSensitive() ? BinaryObject.class.getSimpleName() : "BinaryObject",
"idHash", idHash, false,
"hash", hash, false,
"typeId", typeId(), true);
handles.put(this, idHash);
SB buf = new SB(meta.typeName());
if (meta.fieldNames() != null) {
buf.a(" [idHash=").a(idHash).a(", hash=").a(hash);
for (String name : meta.fieldNames()) {
Object val = fieldForToString(ctx, name);
buf.a(", ").a(name).a('=');
appendValue(val, buf, ctx, handles);
}
buf.a(']');
}
return buf.toString();
}