Reputation: 9646
Needs:
contains
to check whether a certain object is stored in the structurecontains
returns true then fetch that specific object from the structure and call a certain getter
on that objectOptions I've considered:
Map - this works for all the needs but I don't really have a map (key and a value). all I have is bunch of objects. Would it be a good practice to forcefully use a map by storing objects as key and integer or something in the value?
Set would work, however, it doesn't have a fetch method like get.
contains
returns true I'll have to loop through the list to find the index of my particular object and then fetch it. I'm open to using different libraries like apache commons or guava for example.
Upvotes: 4
Views: 145
Reputation: 36904
List would also work, but it doesn't have a method to fetch that is non index based.
List
has an indexOf(Object)
method which will do exactly what you want.
Upvotes: 2
Reputation: 9180
You need a set. You don't need a fetch method (you think you do), because like you said you only have a bunch of objects. And since these use equals
and hashCode
, a set is exactly what you need.
Of course a map could do as well, because its keys is a set as well, but in the end you need to better specify your requirements, as it appears you are a bit confused as to the purpose of your data structure. From what I understand, you do not need a map indeed.
A hash set implementation will do. Here is what you can do with it all:
class Foo
{
final String name;
Foo(String name)
{
this.name = name;
}
boolean equals(Object obj)
{
return (obj instanceof Foo) && ((Foo)obj).name.equals(name);
}
}
Set<Foo> fooSet = new HashSet<Foo>();
fooSet.add(new Foo("someFoo"));
assert fooSet.contains(new Foo("someFoo"));
Upvotes: -2
Reputation: 213401
Although the best thing
to use in this scenario
would be a Map
, because it offers fast retrieval based on Key-Value
pair.
But List
also allows to fetch data based on index.
So, you can use either a List
or a Map
. But to make your task easier, I would prefer a Map
. Because i case of Map
you won't have to search for an index
of an Object, then get the Object
at that index. Fetching is just a one-line
operation.
// When using a List.
List<String> myList = new ArrayList<String>();
if (myList.contains("rohit")) {
myList.get(myList.indexOf("rohit"));
}
// When using Map.
Map<String, String> myMap = new HashMap<String, String>();
// You can directly fetch your object, based on some Key if you have one..
myMap.get("key");
Upvotes: 2