birdy
birdy

Reputation: 9646

which datastructure should i use based on my needs?

Needs:

Options I've considered:

I'm open to using different libraries like apache commons or guava for example.

Upvotes: 4

Views: 145

Answers (3)

Baz
Baz

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

Armen Michaeli
Armen Michaeli

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

Rohit Jain
Rohit Jain

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

Related Questions