当Java中的类不覆盖hashCode()时,打印此类的实例会给出一个很好的唯一编号.
对象的Javadoc说关于hashCode():
尽可能合理,Object类定义的hashCode方法确实为不同的对象返回不同的整数.
但是当类重写hashCode()时,我怎样才能获得它的唯一编号?
我正在寻找一个类似于ArrayList的java数据结构,当我只使用一个值参数进行添加或推送时,将自动为我返回一个索引.
例如:
ArrayList<String> elements = new ArrayList<String>();
String element = "foo";
String elementTwo = "bar";
int index1 = elements.add(element); //note this does not exist, i.e. returns bool in api
int index2 = elements.add(elementTwo);
System.out.println(elements.get(index1)); //would give "foo"
Run Code Online (Sandbox Code Playgroud)
我可以看到围绕ArrayList编写一个包装类来管理一个计数器,该计数器在每次添加操作时都会递增并调用:
ArrayList.add(int index, E element)
Run Code Online (Sandbox Code Playgroud)
你真的需要为ArrayList编写一个包装器吗?这似乎很简单,可以在某个地方开箱即用?
编辑:
我需要为此用例修复和唯一索引(键).提出了一张地图,我同意这一点.有没有人知道一个地图实现,它会在值插入上为您提供自动(唯一)生成的键?我只是想确定是否需要为此实现自己的包装器.
我正在制作一个调度(调度员?)程序。当我设法创建“addReport”方法时,我在显示所有报告(遍历地图)时遇到了问题。我认为每次我尝试添加新元素时,它们都会被替换,因为标识符 (UUID) 是相同的。你怎么看,或者可能是不同的东西?
public class Dispatching {
private String identificator;
private Map<String, Report> reportMap;
public Dispatching() {
this.identificator = UUID.randomUUID().toString();
this.reportMap = new HashMap<>();
}
void addReport(String message, ReportType type) {
reportMap.put(identificator, new Report(type, message, LocalTime.now()));
}
void showReports() {
for (Map.Entry element : reportMap.entrySet()) {
System.out.println("uuid: " + element.getKey().toString()
+ " " + element.getValue().toString());
}
}
}
public class Report {
ReportType reportType;
String reportMessage;
LocalTime reportTime;
public Report(ReportType reportType, String reportMessage, LocalTime reportTime) {
this.reportType = reportType;
this.reportMessage …Run Code Online (Sandbox Code Playgroud)