比较链表中的元素

时间:2014-03-04 21:46:40

标签: java linked-list queue

我有一个队列实现,如下所示。

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。

1 个答案:

答案 0 :(得分:3)

以下是对我的评论的解释,“尝试为字符串创建自定义类并实现Comparable界面。然后您可以编写自己的compareTo方法。”

看到你有一个非常特殊的数据类型,你可以创建自己定义的类。以下MyString类封装了一个String,实现了Comparable接口,并提供了一个如何对这样的类使用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.再次,这只是一个示例,我只是比较字符串。以下是使用此方法比较两个格式化字符串的示例:

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));

ComparablecompareTo上的文档可以找到here