这里是对我的评论的解释,“尝试为您的字符串创建一个自定义类并实现Comparable
接口,然后您可以编写自己的compareTo
方法。”
由于您拥有非常特定的数据类型,因此您可以创建自己定义的类。以下MyString
类封装了字符串,实现了接口,并提供了如何使用compareTo
方法处理此类的示例。
public class MyString implements Comparable<MyString> {
private String data;
public MyString(String data) {
this.data = data;
}
public int compareTo(MyString other) {
String[] thisArray = new String[6];
String[] otherArray = new String[6];
thisArray = this.data.split(" ");
otherArray = other.data.split(" ");
// Compare each pair of values in an order of your choice
// Here I am only comparing the first two number values
if (!thisArray[0].equals(otherArray[0])) {
return thisArray[0].compareTo(otherArray[0]);
} else if (!thisArray[1].equals(otherArray[1])){
return thisArray[1].compareTo(otherArray[1]);
} else {
return 0;
}
}
}
的compareTo
方法返回1,0,或-1取决于值A是否是分别大于,等于,或大于值B同样较小,这仅仅是一个例子,我只比较字符串。这里是一个如何比较两个使用这种方法,您格式化字符串的例子:在Comparable
和compareTo
MyString a = new MyString("1 0 2014/03/03 01:34:39 0.0 0.0 0.0");
MyString b = new MyString("1 1 2014/03/03 01:34:40 0.0 0.0 0.0");
// Do something with the compared value, in this case -1
System.out.println(a.compareTo(b));
文档可以发现here。
问题是?\ – kosa
*我想比较每个字符串*的这些条目,请解释您想如何比较它们。 –
我不太明白AlllsWell的问题。你想让我们为你写一个比较方法吗? *你做了什么 – Fallenreaper