' P '

whatever I will forget

Java LinkedListの中身をアルファベット順に並び替える compareTo()の使い方も。

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;
        }
    }
}