2014-03-04 178 views
0

我有一个队列实现,如下所示。比较链接列表中的元素

static String a = "1 0 2014/03/03 01:34:39 0.0 0.0 0.0"; 
static String b = "2 1 2014/03/03 01:34:40 0.0 0.0 0.0"; 
static String c = "3 2 2014/03/03 01:34:41 0.0 0.0 0.0"; 
static String[] d; 
String e; 
public static void main(String[] args) { 

    Queue<String> s = new LinkedList<String>(); 
    s.add(a); 
    s.add(b); 
    s.add(c); 
    } 

正如你看到列表中的每个条目是具有7种元素的字符串。我想比较每个字符串中的这些条目。例如,a,b,c使用s的第一个条目。

+0

问题是?\ – kosa

+3

*我想比较每个字符串*的这些条目,请解释您想如何比较它们。 –

+0

我不太明白AlllsWell的问题。你想让我们为你写一个比较方法吗? *你做了什么 – Fallenreaper

回答

3

这里是对我的评论的解释,“尝试为您的字符串创建一个自定义类并实现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同样较小,这仅仅是一个例子,我只比较字符串。这里是一个如何比较两个使用这种方法,您格式化字符串的例子:在ComparablecompareTo

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