问题我需要id为每个Person对象创建一个唯一的。public interface Person { String getName();}public class Chef implements Person{ String name; .... // all other instance variables are not unique to this object.}public class Waiter implements Person{ String name; .... // all other instance variables are not unique to this object.}额外的信息中的所有其他实例变量Chef对于特定的Chef. 我们也不能在Chef类中添加任何额外的变量以使其唯一。这是因为此信息来自后端服务器,我无法修改Chef该类。这是一个分布式系统。我想要做什么我想创建一个整数来映射这个Person对象。我试图创造一个“独特的” id。private int makeId(Person person){ int id = person.getName() .concat(person.getClass().getSimpleName()) .hashCode(); return id;}但是,我知道这并不是真正唯一的,因为名称的 hashCode 不能保证任何唯一性。不使用随机我可以使这个id独一无二吗?很抱歉造成误解,但我无法向我的Chef或Waiter对象类添加更多字段,并且应用程序已分发。
2 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
如果您的应用程序不是分布式的,只需在构建过程中使用静态计数器:
public class Chef {
private static int nextId = 1;
private final String name;
private final int id;
public Chef(String name){
this.name = name;
this.id = Chef.nextId++;
}
}
第一个的 idChef是 1,第二个是 2,依此类推。
如果您的程序是多线程的,请使用AtomicIntegerfornextId而不是 plain int。
只是不要hashCode用作唯一的ID。根据定义,哈希码不必是唯一的。
添加回答
举报
0/150
提交
取消
