Let's have a look at your code. Your method setId
doesn't set an ID, so the name is misleading or you want to have a different functionality.
The code generates a type 4 UUID and gets its most significant 64 bits. Then, there's a cast to type byte
, that is you effectively use only the lower 8 significant bits of the most significant 64 bits of the UUID. 8 bits are 256 different values in the range from -128 to 127. Afterwards you convert them to String, parse this String as int, calculate its absolute value and convert it back to String.
In the end, you'll get a random value between 0 and 255 (incl.), represented as String which you can get also by e.g. Integer.toString((int)(Math.random() * 256))
, or rand.nextInt(256)
with rand
being of type java.util.Random
.
Back to the naming of the method. It's unclear if this is a utility method or if it is part of your Employee class (btw: type names are written in UpperCamelCase in Java by convention, so it's class Employee instead of employee).
I'll assume you want this method to be part of the Employee class, so the question is, how can you set the ID of some employee?
public class Employee {
private String id; // the id of the employee
public final void setId() {
id = Integer.toString((int)(Math.random() * 256));
}
// ...
}
If you now call
Employee emp1 = new Employee("sarah", 2500,300);
emp1.setId();
the id of emp1 will be set. Usually you want this to happen at the time the object is constructed, so you call this method inside the constructor. Then, you can optionally make this method private to prevent it from being called by objects of some other type (you encapsulate the functionality).
Apart from that you should think about using the UUID directly (e. g. member variable declaration private UUID id;
) because a random number out of 256 is very likely to produce duplicates which is not the purpose of an ID.