Question

In order to create a client object with a unique ID i was thinking of doing this (see below). Will this newly created object be assigned with a randomly generetad String and added to the object, and then the List? Will I be able to access it later? (Sorry for the incompetence).

Have no way of testing as of yet.

List<Client> newCli = new ArrayList<Client>();

 String uniqueID = UUID.randomUUID().toString();

            Client Client = new Client(name1, name2, addrName, addrNumber, post, city, uniqueID);


            newCli.add(Client);

Client refers to a Class with variables and a constructor with the parameters as seen below.

Thanks a bunch!

Was it helpful?

Solution

That is very likely to work. Note that UUIDs aren't necessarily unique, just very probably, and if you're generating a type 4 UUID, there's an extremely small but nonzero chance that there will be a collision. Generating UUIDs based on names (perhaps a canonical representation of the variables) or including information about the generating computer can help reduce the chances of a collision when multiple systems are generating UUIDs simultaneously.

OTHER TIPS

I agree with chrylis that this approach should work the vast majority of the time, after you change your variable name to "client" so that there isn't confusion with the Client class name.

Another approach is to use a static variable that is an AtomicLong, initialized to either zero or some value from a database. Each time you need a uniqueId, use incrementAndGet() which will atomically increment the variable and return the value, which you will use as your uniqueId.

When using Hibernate/JPA and needing a uniqueId on each new record, I just set the id column to autoincrement and let the database handle it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top