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();
	}

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

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().

Edited 3 Years Ago by mvmalderen

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).