【发布时间】:2014-07-15 19:54:44
【问题描述】:
我正在尝试对以下字符串进行排序
1.0.0.0-00000000-00000
2.1.0.0
2.2.0.0
2.3.0.0-00000000-00000
我目前将这些值保存在一个字符串数组中。
String[] arrays = {"1.0.0.0-00000000-00000", "2.1.0.0", "2.2.0.0", "2.3.0.0-00000000-00000"};
我试图有一个输出,如果没有“-”,那么这些值会按排序顺序到达我的数组的末尾。我正在尝试输出如下:
1.0.0.0-00000000-00000
2.3.0.0-00000000-00000
2.1.0.0
2.2.0.0
我已经尝试过Arrays.sort(arrays),但我不确定如何进行排序?
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collections;
public class HelloWorld{
public static void main(String []args){
String[] arrays = {"1.0.0.0-00000000-00000", "2.1.0.0", "2.2.0.0", "2.3.0.0-00000000-00000"};
String[] newArray = new String[arrays.length];
class CustomComparator implements Comparator<String>
{
@Override
public int compare(String a, String b)
{
if(a.contains("-") && !b.contains("-"))
return 1;
else if(!a.contains("-") && b.contains("-"))
return -1;
return a.compareTo(b);
}
}
Arrays.sort(arrays, new CustomComparator());
for(String array : arrays)
{
System.out.println(array);
}
}
}
Error:
$javac HelloWorld.java 2>&1
HelloWorld.java:25: error: no suitable method found for sort(String[],CustomComparator)
Collections.sort(arrays, new CustomComparator());
^
method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
(no instance(s) of type variable(s) T#1 exist so that argument type String[] conforms to formal parameter type List<T#1>)
method Collections.<T#2>sort(List<T#2>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
1 error
The method gave me an output of
2.1.0.0
2.2.0.0
1.0.0.0-00000000-00000
2.3.0.0-00000000-00000
as opposed to
1.0.0.0-00000000-00000
2.3.0.0-00000000-00000
2.1.0.0
2.2.0.0
【问题讨论】:
-
尝试使用
string.contains("-") -
您可以编写自定义比较 - 但这与排序算法没有任何关系(排序算法只需要一个相对排序函数)。请参阅docs.oracle.com/javase/7/docs/api/java/util/…(或数组的等效项)
-
您需要自定义
Comparator。Arrays.sort有一个重载,它接受一个作为参数。 -
还要注意
Arrays.sort的一些重载是稳定的,所以如果创建一个给出正确顺序的Comparator似乎很难,使用稳定排序进行两次排序可能更容易(就像你可以首先按名字排序人员表,然后按姓氏,以获得正确的姓名顺序)。 -
对数组使用 Arrays.sort