排序的ArrayList不显示?

时间:2012-05-21 21:00:47

标签: java arrays list sorting

ArrayList <String> cdcollection = new ArrayList();

private void initButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Collections.addAll(cdcollection, "renier\n",  "mert\n", "rain\n", "mylen", "dreb\n"    );
    initButton.setEnabled(false);
}

private void displayButtonActionPerformed(java.awt.event.ActionEvent evt) {

    String title1 = "Original Order\n\n";
    String title2 = "Sorted Order\n\n";

    String collection = "";
    for (int i = 0; i < cdcollection.size(); i++)  {
        collection = collection + cdcollection.get(i);
    }
    mainTextArea.setText(title1 + collection);

    Collections.sort(cdcollection);

    for (int j = 0; j < cdcollection.size(); j++)  {
        mainTextArea.setText(title2 + collection.get(j));
    }
}

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    cdcollection.add(cdtitleInput.getText());
}

private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    cdcollection.remove(cdcollection.size()-1);
}

这行mainTextArea.setText(title2 + collection.get(j));我收到错误“找不到符号”,并且在运行程序时不会显示。我所看到的就是:

原始订单

renier
MERT

mylen
DREB

1 个答案:

答案 0 :(得分:0)

您已将collection定义为String collection = "";之类的字符串。 String类中没有名为get(j)的方法。尝试使用你的arraylist对象cdcollection。还可以创建arraylist。您已经完成ArrayList <String> cdcollection = new ArrayList();,尝试使用ArrayList <String> cdcollection = new ArrayList<String>();这样的泛型,否则您可能会收到不必要的警告。

编辑:

public static void main(String[] args){
    ArrayList<String> cdcollection = new ArrayList();
    Collections.addAll(cdcollection, "renier\n", "mert\n", "rain\n",
            "mylen", "dreb\n");

    String title1 = "Original Order\n\n";
    String title2 = "Sorted Order\n\n";

    String collection = "";
    for (int i = 0; i < cdcollection.size(); i++) {
        collection = collection + cdcollection.get(i);
    }
    System.out.println(title1 + collection);

    Collections.sort(cdcollection);
    System.out.println(cdcollection);
}