Say you had this DTO class:
public class MyObj{
private int id;
private String displayName;
private String backendData;
public boolean equals(Object obj){
return id.equals(obj);
}
private int hashCode(){
return id.hashCode();
}
}
Lets say a user got to pick several instances of MyObj from a list that only showed the displayName and the id# is associated in the background. To save bandwidth, you don’t send backendData. When they submit their selection back to you, the client just sends you the id#.
Now, you’ve maintained the list of original options server side in a Collection<MyObj>. The naive approach to geting the “full” object back from the collection would be to iterate through the Collection and call “.equals()” on every object. This scales in O(n) though 🙁
It seems like with constant time operations collections like HashSet, I should be able to retrieve an object in constant time, if I know it’s identity. But HashSet only has a “contains()” method and doesn’t return the object it found.
Any advice? As always, thanks a bunch stackOverFlow!
I assume id is unique across the collection?
You are almost there use a
Map<Integer, MyObj>thenmap.get(id)is asymptotically constant time.