compareTo()
メソッドを使用する。
Stringタイプでも使用できるのはすごい。Unicode順で差分を出すらしい..
とりあえずcompareTo()の結果値を覚えておく
前提:stringA.compareTo(stringB);
とする
- 返り値が0: 同じ値の比較
- 返り値が0以上: stringAのほうが大きい(文字列ならstringAのほうがZ
に近い)
- 返り値が0以下: stringBのほうが大きい(文字列ならstringBのほうがZ
に近い)
ListIterator
何やらListIterator
というのがでてきた
どうやらIterator
のパワーアップ版らしい
とりあえず着目すべきなのは、前のindexに戻れることです。
なのでcompareTo()
で比較したあと、現在のindexデータが比較対象と比べてZ
に近い場合、
一旦indexを戻してそこにデータを挿入してます。
import java.util.LinkedList; import java.util.Iterator; public class main { public static void main(String[] args) { LinkedList<String> thePlaces = new LinkedList<String>(); thePlaces.orderAndAddList(thePlaces, manman); thePlaces.orderAndAddList(thePlaces, chinman); thePlaces.orderAndAddList(thePlaces, unkoman); thePlaces.orderAndAddList(thePlaces, peroman); thePlaces.orderAndAddList(thePlaces, oppaiman); printList(thePlaces); } public static void printList(LinkedList<String> list) { Iterator<String> i = LinkedList.Iterator(); while(i.hasNext()) { System.out.println("The place: " + i.next()); } } public static boolean orderAndAddList(LinkedList<String> linkedList, String thePlace) { ListIterator<String> stringIterator = linkedList.listIterator(); while(stringIterator.hasNext()) { int comparison = stringIterator.next().compareTo(thePlace)); if(comparison == 0) { //equal System.out.println("The place is already existed!") return false; } else if(comparison > 0) { //the current data is bigger than the parameter (thePlace) stringIterator.previous(); stringIterator.add(thePlace); return true; } else if(comparison < 0){ //nothing to do. (Because it's already alphabetical order) } //it's already alphabetical order //add parameter data at the end of list stringIterator.add(thePlace); return true; } } }