Checking the HashMap Key Variable

My problem is that I have a HashMap where the key is an object and I need it to be one of the variables in the specified object. Currently, HashMap.get () is only looking at myNums objects, but I need a way to get the value num1 as a "real key". I cannot use myNums.get () methods because I do not have an instance of myNums. I check every item in the HashMap to check, but I would prefer not to. Is there a more elegant solution?

What I have:

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... } 
+4
source share
2 answers

Perhaps input iteration serves your purpose:

 for (Entry<MyNums, String> entry : map.entrySet()) { System.out.println("Key:" + entry.getKey()); System.out.println("Value:" + entry.getValue()); } 

With this iteration style, you don't need to constantly refer to get .

+1
source

You must override the hashCode () method and extend the equals () method of your class.

 private class myNums{ public int hashCode(){ //Return something unique } public boolean equals(myNums that){ return this.num1==that.num1; } } 
0
source

All Articles