rokkonet

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

java 2つの文字列の文字列長比較

2021 Jun. 26.
2020 Apr. 30.
2019 May 06.


CompStringLength.java

import java.util.Comparator;

public class CompStringLength implements Comparator {
    @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;
        }

        // 文字列長でソート。文字列数がが小さい順に並べる。
        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;
    }
}