問題我需要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
提交
取消