0

次の機能を実装する必要があります。私は最高のクラスを使用することにオープンですが、SortedSet と TreeSet のどちらを使用すべきかわかりません (Set myEmailsAscending = new TreeSet(new DateAscendingComparator()); // メールは常に昇順です)。

public void addEmail(Email email)//The prototype isn't to be altered.
{
Comparator comp;
if(getCurrentSortingMethod()=="DateDescending") comp=DateDescendingComparator;
else if(getCurrentSortingMethod()=="DateAscending") comp=DateAscendingComparator;
...//other comparators

int index = Collections.binarySearch(getEmails(), email, new comp());// Search where to insert according to the current sorting method.
getEmails().add(-index-1, email);}// Add the item to the list
}

それはコンパレータを選択するための適切な構文ですか? 複数の Comparator クラスを作成したくないので、これを行う方法はありますか?

4

2 に答える 2

1

いくつかの問題があります:

equals()文字列の比較には使用する必要があります。ではありません==

の使い方newが間違っています。私は次のことを提案します:

Comparator comp;
if (getCurrentSortingMethod().equals("DateDescending")) {
   comp = new DateDescendingComparator();
} else if (getCurrentSortingMethod().equals("DateAscending")) {
   comp = new DateAscendingComparator();
} ...

int index = Collections.binarySearch(getEmails(), email, comp);

ブロックnew内でがどのように移動されたかに注意してください。if

SortedSet<Email>これらすべての代わりに、適切なコンパレータでを使用することもできます。セットは自動的に正しい順序でソートされたままになります。

于 2012-04-24T17:40:01.033 に答える
0

クラス コンストラクターで Comparator を受け入れるか、そのためのセッターを提供します。次に、 Comparator 内で Comparator を使用しますaddEmail(Email email)。コンパレータが設定されていない場合は、自然順序付けを使用します。

TreeSetを見て、コンパレータと自然順序付けをどのように処理するかを見てください。独自のリストの実装に合わせて調整してください。

于 2012-04-24T17:47:31.260 に答える