Is there a Java collection (or similar) that behaves like an SQL table with an automatic identifier?

Note that I'm not actually doing anything with the database, so the ORM tools are probably not what I'm looking for.

I want to have several containers, each of which contains several objects, and all objects in one container have one class. The container should display the behavior of the database table, namely:

  • allows you to use one of the fields of the object as a unique key, i.e. E. Other objects that have the same value in this field are not added to the container.
  • after accepting a new object, the container should issue a numerical identifier that is returned to the calling insert method.

Instead of throwing an error when a β€œrepeat entry” is requested, the container should just skip pasting and return the key of an existing object.

Now I would write a generic container class that accepts objects that implement the interface to get the key field value, and use a HashMap with these values ​​as a real storage class. Is there a better approach using existing built-in classes? I was browsing through HashSet and the like, but they didn't seem to fit in.

+6
java collections data-structures
source share
4 answers

None of the Collections classes will do what you need. You will have to write your own!

PS You will also need to decide whether your class will be thread safe or not.

PPS ConcurrentHashMap is close, but not quite the same. If you can subclass or wrap it or wrap objects that enter your card so that you rely only on this class to ensure thread safety, you will get an efficient and thread safe implementation.

+4
source share

You can model this behavior using a HashSet . If the objects you add to the collection have a field that you can use as a unique identifier, just get that field returned by the hashCode () method of the object (or use the calculated hash code , any of them should work).

HashSet will not throw an error if you add a duplicate, it just returns false. You can wrap (or extend) the HashSet so that your add method returns the unique identifier that you want as the return value.

+3
source share

I thought you could do this with an ArrayList, using the current location in the array as "id", but that does not stop you from pasting into an existing location, plus when you paste into that place, it will move everything. But you can create your own class in ArrayList by returning the current .size () value after .add.

+1
source share

Is there a reason why the hash code of an object cannot be used as a "numeric identifier"?

If not, all you have to do is wrap the call in ConcurrentHashMap, return the hashCode object and use the putIfAbsent (K key, V value) method to make sure that you are not adding duplicates.

putIfAbsent also returns an existing value, so you can return its hash code for your user.

See ConcurrentHashMap

+1
source share

All Articles