简体   繁体   中英

Java Hashmap/Hashtable and numbering

the question is simple - I have to implement JTree TreeModel interface which requires that every object has a number. The tree will represent data that are kept in hashmap/hashtable. Keys in that hashmap are client objects and values are arrays of resources (or ArrayLists) so numbering is only a problem at the top level. What would be the easiest way to number keys in Hashmap/Hashtable?

public class IndexedMap<V> extends HashMap<Long, V> {
    private AtomicLong index = new AtomicLong();

    public void put(V value) {
        put(index.getAndIncrement(), value);
    }
}

IndexedMap<Object> objects = new IndexedMap<Object>();
objects.put("foo");
objects.put("bar");
// ...

But why don't you just use an ArrayList ? It holds objects by an index, exactly what you need.

Sounds like the user-object keys need to be ordered - their "number" would be derived from their spot in the ordering.

Are the keys Comparable? If so, maybe use a TreeMap. If not, I suppose insertion order is your best bet (LinkedHashMap)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM