Long UUID

sid78669

I was trying to set a UniqueIdentifier based on Long. The objective was to give a certain custom Object a unique identifier in order to allow me to store them in a hashmap. I saw someone trying to use the most significant bits. So I realized that the addition of least and most significant bits will make it work. Here it is for anyone looking for a long UUID.

412 Views
About the Author

I might be a geeky person, but I love to play actual sports, i.e. Soccer and Swimming and Hockey more than computer games. My favorite thing to do, for pleasure, is go on long 6-10 hour drives! Computers were a hobby till i figured it would be easier for me to get good grades and maintain a wonderful GPA in University, which in turn made me switch from Political Science to Computers Science ;)

private void setUniqueIdentifier() {
		UUID initUUID = UUID.randomUUID();
		uniqueIdentifier = initUUID.getLeastSignificantBits() + initUUID.getMostSignificantBits();
	}
JamesCherrill 4,394 Most Valuable Poster Moderator Featured Poster

For re-usability it would be better to return the long value, rather than set a fixed named variable that's declared elsewhere?

mvmalderen 2,072 Postaholic

For re-usability it would be better to return the long value, rather than set a fixed named variable that's declared elsewhere?

In addition it would be a good idea then to also rename the method to getUniqueIdentifier().

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Minor stuff aside, this snippet has other problems. UUID is unique because of all the bits it has. Substring of a random number itself isn't random. If you'll read the UUID specification (which I think the UUID class follows), the different range of bits in an UUID stands for different components. You can't pick them apart and expect them to be unique. My personal vote goes out to the nextLong method of the SecureRandom class. You get a long datatype back and it's crptographically strong.

On a related note:

The objective was to give a certain custom Object a unique identifier in order to allow me to store them in a hashmap

IdentityHashMap doesn't work for you? Also, for live objects, identityHashcode is also unique since it is basically the memory address of that object which has to be unique unless we end up re-using the address space (which happens something is garbage collected hence the warning that it works only for live objects).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.