我想为某些属性创建一个独一无二的对象:
import java.util.HashMap;
public class SourceLanguage {
private final String name;
private static HashMap<String,SourceLanguage> existing;
private SourceLanguage(String name){
this.name = name;
}
public String getName(){
return name;
}
public static SourceLanguage get(String name){
if(existing==null){
existing = new HashMap<>();
SourceLanguage sl = new SourceLanguage(name);
existing.put(name.toLowerCase(),sl);
return sl;
}
SourceLanguage check = existing.get(name);
if(check==null){
SourceLanguage sl = new SourceLanguage(name);
existing.put(name.toLowerCase(),sl);
return sl;
}else {
return check;
}
}
}
我想将此类的对象用作另一个地图中的键。
我觉得有点矫枉过正。有没有更简单的方法来实现目标?