我的问题是我有一个HashMap,其中键是一个对象,我需要它作为所述对象中的一个变量。目前,HashMap.get()仅查看myNums对象,但我需要一种方法来获取num1的值,因为它是"真正的键"。我无法使用myNums.get()方法,因为我没有myNums的实例化。我想循环遍历HashMap中的每个项目以进行检查,但我不想这样做。有更优雅的解决方案吗?
我有什么:
public static void main(String [] args){
int [] array = {//integers 1-100};
HashMap < myNums, String > hash = //data from another source;
for(int i = 0;i < array.length; i++){
if(hash.get(i) != null)
OtherFunction(hash.get(i));
}
}
public class myNums{
private int num1;
private int num2;
//get and set functions...
}
答案 0 :(得分:1)
也许一个条目迭代更符合你的目的:
for (Entry<MyNums, String> entry : map.entrySet()) {
System.out.println("Key:" + entry.getKey());
System.out.println("Value:" + entry.getValue());
}
使用此迭代样式,您不必一直调用get
。
答案 1 :(得分:0)
你应该覆盖hashCode()方法并扩展你的类的equals()方法。
private class myNums{
public int hashCode(){
//Return something unique
}
public boolean equals(myNums that){
return this.num1==that.num1;
}
}