Solved

Searching a list using a generic instance of a class

Posted on 2004-09-02
11
255 Views
Last Modified: 2010-03-31
I'm trying to implement a list where I'll be storing specific instances of objects, but where I need to be able to find elements in the list based on traits they share in common with generic objects.

Basically, my stored classes have the attibutes "name" and "number".  I can have more than one of a given pairing of those, I just need the basic ability to find the *first* match in the list based on either those two pieces of data, ideally by passing a similar object to a search routine and having it find the first match.

Although it is possible to impose an ordering on the items, it's not really natural to do so, and there's a fair number of ways to cause it to mess up, since the items are grouped, but the groups don't have a natural ordering.
0
Comment
Question by:offline314159
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 11965218
Simply compare each object's value with the one on the List. Stop at the first one. For example if you have an object called Info with "name" and "number" attributes and a list "myList" you might as well do:

Info info toBeSearchedFor = new Info("girionis", 10);

for (int i=0; i<myList.size(); i++)
{
   Info info = (Info) myList.get(i);
   if (info.getName().equals(toBeSearchedFor.getName()) && info.getNumber() == toBeSearchedFor.getNumber())
   {
      // do whatever you want with the object.
      // you might as well return it, in this cae you do not need th ebreak statement below
      break;

   }
}
0
 

Author Comment

by:offline314159
ID: 11965280
I was hoping for something a bit less in the O(n) range for searching.  I was thinking of using a binary search, but I think that rests on the equals() method as well, and I don't want to override that for other reasons of my own.  Not to mention the fact that any ordering I impose on these items will be a bit of a kludge.

If all else fails, I guess I'll go linear on it, but that's just excessively inefficient from where I sit.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 125 total points
ID: 11965353
binarySearch is exactly what you need:

Info infoToBeSearchedFor = new Info("girionis", 10);
Collections.binarySearcch(yourList, infoToBeSearchedFor, new Comparator() {
      public int compare(Object o1, Object o2) {
            Info info1 = (Info)o1;
            Info info2 = (Info)o2;
            return info1.getName().hashCode() + info1.getNumber() - info2.getName().hashCode() + info2.getNumber();
      }
});
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 11965365
Typo there:

>>Collections.binarySearcch

should obviously be

Collections.binarySearch

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11965402
Oh - and you'll need to use the return value from that method too ;-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11965431
>  I was thinking of using a binary search

Binary search will work on sorted items. I seem to remember you said that groups do not have a natural ordering. Do they have any ordering at all?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11965498
It's the Comparator that does the ordering. Brackets required here:

return (info1.getName().hashCode() + info1.getNumber()) - (info2.getName().hashCode() + info2.getNumber());

(Not quite awake yet ;-))
0
 

Author Comment

by:offline314159
ID: 11965651
Hrm.  So, if I force an ordering on them -- whether via implementing the Comparable interface or writing a quick and dirty comparator -- I'll be able to do that?  I can kludge an ordering that just arbitrarily ranks the name field and then use that.  Collections.binarySearch never uses the equals() method at all, then?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11965696
>>I can kludge an ordering that just arbitrarily ranks the name field and then use that

Yes

>>Collections.binarySearch never uses the equals() method at all, then?

Not with the method that passes a Comparator

0
 
LVL 21

Expert Comment

by:MogalManic
ID: 11965717
Another option is to use the TreeMap class.  Your key can be the "name" and "number".  To find the closest match you can use the headMap(key) and tailMap(key) methods.  To iterate through your list you can either use map.Values(), or Arrays.asList(map.values()).get(idx)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11966735
8-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
CSV file parsing thru Java 13 54
Java array 21 150
Eclipse neon2 "Java build path" correctness 7 43
Retrieve multiple results between delimiters in a String in Java 13 24
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This video teaches viewers about errors in exception handling.
Suggested Courses

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question