Solved

Searching a list using a generic instance of a class

Posted on 2004-09-02
11
216 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
  • 6
  • 2
  • 2
  • +1
11 Comments
 
LVL 35

Expert Comment

by:girionis
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Typo there:

>>Collections.binarySearcch

should obviously be

Collections.binarySearch

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Oh - and you'll need to use the return value from that method too ;-)
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 35

Expert Comment

by:girionis
Comment Utility
>  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
Comment Utility
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
Comment Utility
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
Comment Utility
>>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
Comment Utility
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
Comment Utility
8-)
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

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…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now