【问题标题】:Comparing elements in a linked list比较链表中的元素
【发布时间】:2014-03-04 21:46:39
【问题描述】:

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

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 个元素的字符串。我想比较每个字符串中的这些条目。例如使用 s 的 a、b、c 的第一个条目。

【问题讨论】:

  • 问题是?\
  • 我想比较每个字符串中的这些条目请说明您希望如何比较它们。
  • 我不太明白 AlllsWell 的问题。你想让我们为你写一个比较方法还是什么? 做了什么
  • 您可以尝试为您的字符串创建一个自定义类并实现Comparable 接口。然后你可以编写自己的compareTo 方法。
  • TL:DR;这正是@ElliotSchmelliot 所做的。 :)

标签: java linked-list queue


【解决方案1】:

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

鉴于您有一个非常特殊的数据类型,您可以创建自己定义的类。以下MyString 类封装了一个字符串,实现了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 找到。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2015-09-30
    • 2020-02-21
    • 1970-01-01
    • 2023-04-03
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多