課題として、LinkedList の順序付きバージョンと順序なしバージョンの両方を Java のバッグとして実装するように依頼されました。順序付けされたバージョンは、挿入メソッドをオーバーライドしながら、順序付けられていない実装を単純に拡張します。
挿入機能の順序付けは機能します...多少。与えられたテスト配列
String[] testArray= {"z","g","x","v","y","t","s","r","w","q"};
出力は
q w r s t y v x g z
いつあるべきか
g q r s t v w x y z
ただし、要素の値が混同されていない場合、順序付けは正常に機能します。たとえば、私は最初testArray[]
にアルファベットを逆にして上記を使用しましたが、順序は正しいはずです。
私の追加機能は
@Override
public void add(E e){
Iter iter= new Iter(head.prev);
int compValue;
E currentItem= null;
//empty list, add at first position
if (size < 1)
iter.add(e);
else {
while (iter.hasNext()){
currentItem= iter.next(); //gets next item
//saves on multiple compareTo calls
compValue= e.compareTo(currentItem);
//adds at given location
if (compValue <= 0)
iter.add(e, iter.index);
else //moves on
currentItem= iter.next();
}
}
}
イテレータ機能は次のように実装されます。
//decided to use iterator to simplify method functionality
protected class Iter implements Iterator<E>, ListIterator<E>{
protected int index= 0;
protected Node current= null;
//Sets a new iterator to the index point provided
public Iter(int index){
current= head.next;
this.index=0;
while (index > nextIndex()) //moves on to the index point
next();
}
public void add(E e, int index){
size++;
Iter iterator= new Iter(index);
Node node= new Node();
Node current= iterator.current.prev;
node.next= current.next;
node.prev= current;
node.next.prev= node;
node.prev.next= node;
node.item= e;
}
現在のところ、使用されているのはプリミティブ型だけです。オブジェクトの場合、特定の同等のクラスを作成する必要があることはわかっていますが、この場合、String には正しい順序付けを行う compareTo() メソッドが含まれています。
偶然にも、私の同級生が同様の実装を行っており、同じ結果を返しています。
自然順序付けを使用して、この問題を解決するにはどうすればよいですか?