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.