Reputation: 1262
I am trying to do a lookup for a corresponding value for an entry item in an arraylist (alphanumeric value and its hashcode).
The use of hashmap was dropped to allow duplication of objects(keys).
ArrayList<Object[]> pNArrayList = new ArrayList<Object[]>();
contains
[101E2571G103, -1162488899]
[101E2571G103, -1162488899]
[116E3139P001, -1561106156]
[314B7159G003, -1344220682]
[117E3640G025, -1595019143]
[117E3640G025, -1595019143]
For an input, inputID
of type long
for(int i=0; i< pNHashArrayList.size();i++) {
if(pNArrayList.get(i)[1].equals(inputID)){
System.out.println(pNArrayList.get(i)[0]);
}
else {
System.out.println(pNArrayList.get(i)[0] + " and "+ pNArrayList.get(i)[1] +" No Match Found");
}
}
The else
and SysOut
statement thereafter were included only to cross validate.
output:
101E2571G103 and -1162488899 No Match Found
101E2571G103 and -1162488899 No Match Found
116E3139P001 and -1561106156 No Match Found
314B7159G003 and -1344220682 No Match Found
117E3640G025 and -1595019143 No Match Found
117E3640G025 and -1595019143 No Match Found
I think, the problem might be in the pNArrayList.get(i)[1].equals(inputID)
?. Need some suggestions on this.
Also, my actual dataset will have around 10,000 entires, would the lookup by looping have problem with runtime computations?
Upvotes: 0
Views: 1143
Reputation: 1426
Good approach is suggested by @sharonbn, but you can try this to run your existing code :
if( ((Long)pNArrayList.get(i)[1]) == inputID){
System.out.println(pNArrayList.get(i)[0]);
}
else {
System.out.println(pNArrayList.get(i)[0] + " and "+ pNArrayList.get(i)[1] +" No Match Found");
}
}
Upvotes: 0
Reputation: 14328
I don't know how you build your data structure. However, a better design is to have a Map<Long, List<Object>>
with the Long inputID
as key, and the value can be a List of Object
s that all belong to the same ID. This way you support multiple values for the same key and the lookup is O(1)
regarding the equals, it is Object
's equals that is invoked, rather than Long
one. The proposed data structure should solve this problem as well.
Upvotes: 2