rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

文字列長の比較 java

2020 Apr. 25.
2020 Mar. 21.

import java.util.Comparator;

public class CompStringLength implements Comparator<String> {

    /*
     * return 1: String first is longer than String second
     * return -1: String second is longer than String first
     * return 0: equal
    */

    @Override
    public int compare(String first, String second){
        //null評価
        //両方nullなら等価とする
        if(first == null && second == null){
            return 0;
        }
        //片方nullなら、nullを小さいとする。
        if(first == null){
            return -1;
        }else if(second == null){
            return 1;
        }

        //idの文字列長でソート。文字列数がが小さい順に並べる。
        if (first.length() > second.length()) {
            return 1;
        }else if (first.length() < second.length()) {
            return -1;
        }else if (first.length() == second.length()) {
            return 0;
        }
        return 0;
    }
}