Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I'm working on a Java project and I'm wanting the user to enter details about their city.
To do this I have a city class and have the user enter it the values for it's attributes.

The only problem is I'm not sure how to make each instance unique, meaning it has a different name.
Will iterating the name of the new Object instance work?

What I have tried:

I've tried iterating the name of the new Object instance as it will be the same as the previous instance.

I've tried creating a Object Factory.
Posted
Updated 8-Sep-22 5:10am

1 solution

Unless you are creating a small and specific number of instances at compile time, you don't want to "name" them as separate variables.

Instead use a collection: an ArrayList is probably the most basic, or you could use a HashMap and use the Key for the "name" (since city names have to be unique that would work pretty well).

See here for some ideas: Collections in Java - GeeksforGeeks[^]
 
Share this answer
 
Comments
daniel wakeley 8-Sep-22 12:21pm    
Thank you so much Sir, I've been trying for a solution for a while now. I'll add them to a HashMap to give them a unique identifier.
I hope you have a great weekend!
OriginalGriff 8-Sep-22 12:35pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900