2014-02-12 142 views
1

您好我有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

+7

我建議你創建一個'版本'類型,它理解它是一個有序的數字序列,並實現'可比較的' –

回答

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