Generate Unique id using UUID in java

Java provides a class java.util.UUID which can be used to generate a randon UUID. Here is a sample code to create a UUID.

<p>UUID randomUUID = UUID.randomUUID();</p>


<br />
 e617f74f-d0cd-4f17-988f-5a05a94ac63e<br />

So the above code can be used to assign ids to entities e.g;

Suppose you are writing Person java class and want each person to have a unique id, you can use UUID to create a unique id for each person object.

<p>class Person {</p>
<p>   private UUID personUUID;</p>
<p>   private String name;</p>
<p>   private String  phoneNumber;</p>
<p> // here are getters and setters<br />
<p>public Person createPerson(){<br />
   Person person = new Person();<br />
   person.setPersonUUID(UUID.randomUUID());<br />
   person.setName(&quot;Obama&quot;);<br />
   return person;<br />
}<br />

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.