Destructor
Destructor

Reputation: 3284

Search an arraylist containing class for a specific item name

I have a class as:

public class Test_Demo{
    public String name;
}

Now i have an arrayList as:

public ArrayList<Test_Demo> tdArrayList= new ArrayList<Test_Demo>();

Now I create an object of above class as and add it to Arraylist:

Test_Demo td = new Test_Demo();
td.name="Hello";
tdArrayList.add(td);

Now I compare the name as:

String testname="Hello";
for(int i=0;i<tdArrayList.size();i++){
    if(tdArrayList.get(i).name.equals(testname)){
        //name present, print here and break from loop
    }
}

This works fine, but if the ArrayList has many items, this method is slow. Can you suggest me of any better approach?
tdArrayList.contains(testname) wont work because arrayList doesn't have names but it has class that in turn has the name.

Upvotes: 1

Views: 1278

Answers (6)

Joe
Joe

Reputation: 1

How many items in the tdArrayList? And how long does it take you to iterate the whole list? Maybe you can sort the list,and then binary search.

Upvotes: 0

bijilap
bijilap

Reputation: 23

I am not exactly sure of the context. But try answer using hashmap by mapping name and object.

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

Override equals method like following:

public class Test_Demo{
   public String name;
   public boolean equals(Object anObject) {
      if (this == anObject) {
         return true;
       }
     if (anObject instanceof Test_Demo) {
        Test_Demo test = (Test_Demo )anObject;
        if(test.name.equals(this.name)
           return true;
      }   
      return false;
   }
}

And then call contains method.

Upvotes: 0

dg_no_9
dg_no_9

Reputation: 1013

In general terms, this is the best approach. But if you want to improve efficiency, then you may make clusters of ArrayList, such as ArrayList storing names starting with 'A', 'B' and so on. Then if test name is 'Hello' then, get its first letter 'H' and search in the cluster 'H'. You may increase number of clusters depending upon your need. This might be a one solution.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Search an arraylist containing class for a specific item name

There is no way out to see from outside if any class, having that name or not.

You have to iterate and see.

Upvotes: 4

Juned Ahsan
Juned Ahsan

Reputation: 68715

First overrride equals method in your Test_Demo class and then use ArrayList contains method.

Upvotes: 0

Related Questions