All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.plumelib.util.UniqueIdMap Maven / Gradle / Ivy

There is a newer version: 1.10.0
Show newest version
package org.plumelib.util;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Provides a unique ID for classes that you cannot modify. The unique ID is useful because it makes
 * output deterministic. For classes that you can edit, implement the {@link UniqueId} interface.
 *
 * 

The IDs count up from 0, per instance of UniqueIdMap. When you look up an object in this map, * it is given a unique ID if it didn't already have one. * *

Typical use: * *

    *
  1. Define a field: *
    
     * /** Unique ids for trees. */
     * static UniqueIdMap<Tree> treeUids = new UniqueIdMap<>();
     * 
    *
  2. Wherever you would call {@code x.hashCode()}, instead call {@code treeUids.get(x)}. *
* * @param the type of elements that get a unique ID */ public class UniqueIdMap { /** Create a new UniqueIdMap. */ public UniqueIdMap() {} /** The unique ID for the next-created object. */ private final AtomicLong nextUid = new AtomicLong(0); /** A mapping from objects to their IDs. */ private WeakIdentityHashMap map = new WeakIdentityHashMap<>(); /** * Get the unique ID for the given object. If the object's ID has not been previously requested, a * new one is generated for it. * * @param object the object to get a unique ID for * @return the unique ID for the given object */ public long get(E object) { Long id = map.get(object); if (id != null) { return id; } long newId = nextUid.getAndIncrement(); map.put(object, newId); return newId; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy