-3

请任何人都可以帮助我克服这个问题。问题陈述是:

由于某些复选框,我编写了一些代码用于从网页显示用户选择的语言。假设用户为德语和乌尔都语选择了两个复选框,那么我需要在网页上显示德语,乌尔都语。然后在用户再次选择另一种语言选项后阿拉伯语然后我需要在网页上显示,如阿拉伯语、德语、乌尔都语。

谢谢先进。

   knownLanguages ="German,Urdu,Arabic";  
   String userLanguages[] = knownLanguages.split(",");
    for (int i = 0; i < userLanguages.length; i++) {
      if (i == 0)
        knownLanguages1 += userLanguages[i];
      else
        knownLanguages1 += " , " + userLanguages[i];
    }
    List<String> list = new ArrayList<String>(Arrays.asList(knownLanguages1.split(" , ")));
    Collections.sort(list, ALPHABETICAL_ORDER);
    return knownLanguages1;
  }

  private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
      int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
      if (res == 0) {
        res = str1.compareTo(str2);
      }
      return res;
    }
  }; 

但是这段代码没有给出想要的输出。请帮助我。

4

2 回答 2

2

您不需要自定义比较器,因为您所做的只是alphabetical sorting.

以下代码应该适合您:

String knownLanguages ="German,Urdu,Arabic";
// get a list of languages from above string using String#split
List<String> langList = Arrays.asList(knownLanguages.split(","));
// sort the resulting list
Collections.sort(langList);
// print it
System.out.println(langList);
// OUTPUT: [Arabic, German, Urdu]
于 2013-09-20T12:00:59.113 回答
0
   private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
         public int compare(String str1, String str2) {         
             return  str1.compareToIgnoreCase(str2);;
         }      
   }; 
于 2013-09-20T11:32:07.360 回答