Reputation: 976
I have created a new class in which there is an attribute called Name. I am trying to make this attribute ‘unique’. I mean that if I create an object with the name "AA", it will not be possible to create another object named "AA". How can I manage to solve this problem?
EDIT: The problem is that I have to create these objects in another class (let's called it "Main.java").
Upvotes: 2
Views: 3806
Reputation: 393851
One option is to maintain in your class a static Set of all the names previously used. When a new instance is created, you check if the name given to the new instance is already in use (assuming the name is passed to the constructor). If it is, you throw an exception. If not, you add it to the Set.
If you have a public setName
method, you should check the passed name in that method as well, and if the name is not used, remove the old name of the instance from the static Set and add the new name.
public class ObjectWithName
{
private static final Set<String> names = new HashSet<String>();
private String name;
public ObjectWithName (String name) throws SomeException
{
if (!names.add(name))
throw new SomeException();
this.name = name;
}
public void setName (String name) throws SomeException
{
if (names.contains(name))
throw SomeException();
if (this.name != null)
names.remove(this.name);
names.add(name);
this.name = name;
}
}
Note that this implementation is not thread safe, so you'll have to add thread safely if this class may be used by multiple threads.
Upvotes: 3