字符串版本比较

时间:2014-02-12 09:56:43

标签: java

嗨我有String数组

String version[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};

我想找到其中的最新版本。哪种方法会好?它应该打印3.7.3

2 个答案:

答案 0 :(得分:0)

以下是使用Comparator

的示例
public static void main(String[] args) {
    String version[] = { "3.1.2", "2.1.7", "3.1222.1", "3.10.1", "3.10",
            "3.7.3", "2.6.4", "1.3.4.7" };
    Arrays.sort(version, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            //Split tokens into arrays
            String[] tokens1 = o1.split("\\.");
            String[] tokens2 = o2.split("\\.");

            //Compare existing elements of each array
            for (int i = 0; i < tokens1.length && i < tokens2.length; i++) {
                int comparison = Integer.valueOf(tokens1[i]).compareTo(
                        Integer.valueOf(tokens2[i]));
                if (comparison != 0) {
                    return comparison;
                }
            }
            //Compare how specific each version is promote the most general
            //Only considered if version lengths != in size but equal in compared tokens
            return tokens1.length - tokens2.length;
        }

    });

    for (String v : version) {
        System.out.println(v);
    }
}

答案 1 :(得分:0)

试试这个......

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StringSortDemo {

    public static void main(String[] args) throws Exception {

        String strArray[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};
        displayArray(strArray);

        Arrays.sort(strArray);
        displayArray(strArray);

        Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
        displayArray(strArray);

        System.out.println("---------------");

        List<String> strList =Arrays.asList(strArray);
        displayList(strList);

        Collections.sort(strList);
        displayList(strList);

        Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
        displayList(strList);
    }

    public static void displayArray(String[] array) {
        for (String str : array) {
            System.out.print(str + " ");
        }
        System.out.println("The last element is  "+ array[array.length-1]);
    }

    public static void displayList(List<String> list) {
        for (String str : list) {
            System.out.print(str + " ");
        }
        System.out.println("The last element is  "+ list.get(list.size()-1));
    }

}

输出

3.1.2 2.1.7 3.1.1 3.7.3 2.6.4 1.3.4.7 The last element is  1.3.4.7
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is  3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is  3.7.3
---------------
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is  3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is  3.7.3
1.3.4.7 2.1.7 2.6.4 3.1.1 3.1.2 3.7.3 The last element is  3.7.3