【问题标题】:Quadratic sort of ArrayList [closed]ArrayList 的二次排序[关闭]
【发布时间】:2014-07-23 21:53:39
【问题描述】:

我一直在尝试在 java 中使用二次排序来对消息数组列表进行排序。 我使用了以下代码,但它不会为我编译。我不断收到的错误是

找不到变长的符号

以下是我使用的排序和交换:

 public static void quadraticSort(ArrayList<Message> m)


{
    String s1 = "abcd";
    String s2 = "efgh";
    int val = "abcd".compareTo("efgh");

    for (int i = 0; i < s1.length; i += 1)
    {
        for (int s2 = i; s2 < s1.length; s2 += 1)
       {
           if ((int)s1[s2].messageText.compareTo(0) <(int)s2[i].messageText.compareTo(0))

           {
               swap(s1, i, s2);
           }
        }

    } 
}

private static void swap(ArrayList<Message> list, int to, int from)
{
   Message temp = list[to];
   list.set(to , from);
   list.set(from , temp);
}

【问题讨论】:

  • 字符串实例没有length 字段。但是,他们有一个length() 方法。
  • 您还尝试在String 上使用索引器,但这是行不通的。
  • 是的。 Java 中的字符串的行为不像数组,它们是对象。使用"hello".charAt(0) 而不是"hello"[0]

标签: java sorting arraylist


【解决方案1】:

在您的代码中,您尝试访问不存在的 String 实例的 length 属性/字段。相反,您想使用length() 方法:

String s = "abc";
s.length(); // = 3
s.length; // compiler error

但是你有更多的错误。您还尝试使用数组/括号表示法访问字符串的索引值:

s1[s2]

String 对象的字符不能以这种方式访问​​。您应该改用charAt() 方法。

【讨论】:

  • 感谢您的反馈。我已经重构了我的代码,但是编译器告诉我 charAt 不能应用于 int val = 部分的给定类型。
  • 我认为这不是您想要的吗?您可以提出一个单独的具体问题,我会看看。
【解决方案2】:

我建议您阅读 String 的 javadoc。在 Java 中,它们被视为第一类对象;不是字符数组。

要获取字符串的长度,您必须使用length()。此外,要从String 中的给定位置获取字符,您必须使用charAt(int index)

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 2016-08-13
    • 2014-02-18
    • 2017-03-15
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多