Re: Iterator-Related Java Design Problem
From: Oscar kind (oscar_at_danwa.net)
Date: 06/19/04
- Next message: Glenn Robinson: "Re: Can't seem to UPDATE dBase table"
- Previous message: DigiAl: "Re: [J2ME] views wanted for new MIDP-developer site idea"
- In reply to: Ken: "Iterator-Related Java Design Problem"
- Next in thread: Daniel Sjöblom: "Re: Iterator-Related Java Design Problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 19 Jun 2004 11:28:44 +0200
Ken <kk_oop@yahoo.com> wrote:
> I have an unsorted list of Items. Let's say the list is called called
> ItemList.
>
> I need to find the item with the highest priority that also meets some
> other criteria. Let's say that other criteria is called criteria X.
>
> Someone suggested that we approach this by doing the following:
>
> 1- Make a copy of the ItemList [...].
> 2- Sort this copy based on Item priority.
> 3- Sequentially search the prioritized list for the first Item to meet
> criteria X.
>
> I'm thinking a better approach would be to:
>
> 1- Make an iterator [that only returns elements that meet criteria X].
> [2&3- Use the Iterator to manually search the Item with the highest
> priority].
>
> What I like about this latter approach is that it precludes us from
> making a sorted copy of the original list. It also encapsulates
> criteria X in the iterator.
This last part is true, but you'd have to do the search yourself. Also,
you only have the Item with the highest priority: what if the requirements
change and you have to give the 3 top priority Items?
Using the Collections framework is more flexible:
1. Create a Comparator that sorts the elements by priority
2. Create a TreeSet that uses the Comparator
3. Add all Items that match criteria X to the TreeSet
4. Get the first Item of the TreeSet
Since you probably already have the code that checks criteria X, the only
difficult part could be the Comparator. But it isn't:
Comparator priorityComparator = new Comparator()
{
public int compare(Object o1, Object o2)
{
Item i1 = (Item)o1;
Item i2 = (Item)o2;
return i1.getPriority().compareTo(i2.getPriority());
}
}
kind regards,
Oscar
-- Oscar Kind http://home.hccnet.nl/okind/ Software Developer for contact information, see website PGP Key fingerprint: 91F3 6C72 F465 5E98 C246 61D9 2C32 8E24 097B B4E2
- Next message: Glenn Robinson: "Re: Can't seem to UPDATE dBase table"
- Previous message: DigiAl: "Re: [J2ME] views wanted for new MIDP-developer site idea"
- In reply to: Ken: "Iterator-Related Java Design Problem"
- Next in thread: Daniel Sjöblom: "Re: Iterator-Related Java Design Problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|