Long UUID

sid78669 1 Tallied Votes 457 Views Share

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.

private void setUniqueIdentifier() {
		UUID initUUID = UUID.randomUUID();
		uniqueIdentifier = initUUID.getLeastSignificantBits() + initUUID.getMostSignificantBits();
	}
JamesCherrill 4,733 Most Valuable Poster Team Colleague 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?

tux4life 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 meeting, networking, learning, and sharing knowledge.