0
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {

    String newCD = (cdInput.getText());


    List <String> cdList = new ArrayList();
    Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");
    cdList.add(""+newCD);

    List<String> sorted = new ArrayList<String>(cdList);
    Collections.sort(sorted);

    bigBox.setText("");

    bigBox.append("Original Order\n**************\n");

    for (String o : cdList)  {
        bigBox.append(o);
        bigBox.append("\n");
    }

    bigBox.append("\n\nSorted Order\n************\n");

    for (String s : sorted)  {
        bigBox.append(s);
        bigBox.append("\n");
    }
}

使用此代码,我可以添加 1 个值,但是当我尝试添加另一个值时,它会删除原始值并替换它。我能做些什么来防止这种情况发生?

PS。我正在尝试制作一个 CD 列表,并且能够添加新的 CD 并将它们也排序并按原始顺序放置

4

1 回答 1

2

Based on your code, you have no centralised instance of List, which means, each time you activate the button, it has no concept of what was previously in the list.

Start by creating an instance variable of the cd List and only add new items to it as required.

Something more like...

private List<String> cdList = new ArrayList<>(25);

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

    String newCD = (cdInput.getText());
    cdList.add(newCD);

    List<String> sorted = new ArrayList<String>(cdList);
    Collections.sort(sorted);

    bigBox.append("Original Order\n**************\n");

    for (String o : cdList)  {
        bigBox.append(o);
        bigBox.append("\n");
    }

    bigBox.append("\n\nSorted Order\n************\n");

    for (String s : sorted)  {
        bigBox.append(s);
        bigBox.append("\n");
    }
}
于 2013-11-12T22:55:06.830 回答