Implementing an object I'd system in Java.Suggestions?

akashsuresh
akashsuresh used Ask the Experts™
on
Can anyone suggest methods to give unique ids to objects?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2007

Commented:
GUID is frequently used for this.

Or do you mean in a database?  Most db's have a way to request a unique id for a record.  Which one are you using?
hashcode you can use !
It really depends on your requirements.

Do the IDs need to be guaranteed globally unique, or only unique within your particular set of objects?

Are you going to be storing them in a database and, if so, SQL or NoSQL?

Do you need to be able to quickly lookup objects by ID?

Are IDs going to be exposed to users as something they would want to remember?

Are IDs going to be used in a RESTful or other web-based application/service?

As mentioned above, there are several alternatives.

You can use the java.util.UUID class to generate Type 3 (name based) or Type 4 (pseudo random) GUIDs.  Type 4 UUIDs are globally unique and should guarantee that all of your objects have their own ID.  However, if you are going to store them in a database or otherwise search on them, you may need to do some conversions to make them an efficient (non-text-based) search key.

If you are using a backing relational database, such as MySQL or Oracle, you can use the built-in AUTO_INCREMENT or SEQUENCE field types to generate the IDs for you as objects are created.  These IDs will be unique to all objects stored in a particular table (within the range limits of the column).  Since these are integer-based keys, they are easily indexable and searchable and much more manageable for use in URLs if readability is a concern.

The object hash code is another option for an object ID, but the uniqueness of those IDs is largely based on the algorithm you choose to implement the hash code.  If you are just using the Java hashCode() method, you're limited to a 32-bit keyspace (~4 billion elements).  If the hashCode() is derived from the fields of your object, you'll need to determine if two objects can be equal, but different.  For example, if you have a Person object with a name property, can you have two "John Smith" Persons that are not the same object?

Hope that helps!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial