我在java中编写了一个java程序来按字母顺序对字符串进行排序。问题是当它对具有罗马数字的字符串进行排序时,它会将其视为字符并相应地进行排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SampleCustomSortApp
{
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ArrayList<String> titles =new ArrayList();
titles.add("java");
titles.add("J-IV");
titles.add("A-V");
titles.add("J-V");
titles.add("J-IX");
titles.add("J-XX");
titles.add("J-X");
titles.add("J-I");
titles.add("J-II");
titles.add("datawarehouse");
titles.add("oracledba");
System.out.println("Before Sorting Elements Are :"+titles+"\n");
Collections.sort(titles, new MyCustomCompator());
System.out.println("After Sorting Elements Are :"+titles);
}
}
class MyCustomCompator implements Comparator
{
public int compare(Object s1,Object s2)
{
String one = (String)s1;
String two = (String)s2;
/* for ascending order */
if(one.compareTo(two)>0){
return 1;
}else{
return -1;
}
}
}
实际输出
Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]
After Sorting Elements Are :[A-V, J-I, J-II, J-IV, J-IX, J-V, J-X, J-XX, datawarehouse, java, oracledba]
期望的输出
Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]
After Sorting Elements Are :[A-V, J-I, J-II, J-IV, J-V,J-IX, J-X, J-XX, datawarehouse, java, oracledba]
我应该使用正则表达式来比较字符串。有人能告诉我解决方案吗