显示有和没有排序的ArrayList? [英] Displaying an ArrayList with and without sorting?

查看:101
本文介绍了显示有和没有排序的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
排序的ArrayList不显示?

Possible Duplicate:
Sorted ArrayList not displaying?

代码:

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

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

推荐答案

我带了您的代码,但未添加任何代码,并且列表已正确排序.参见下面的代码

I took your code without the swing code and the list is sorted properly. See the code below

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

您在此处使用的for循环

The for loop you used here

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

不要在循环中添加title2,并且在循环中调用setText将覆盖旧文本.将列表中的所有字符串添加到临时字符串中,并添加到mainTextArea中最后一个字符串中.像

Dont add the title2 in the loop and calling setText in loop will over write the old text. Append all the string from the list in a temp string and in the last set in the in the mainTextArea. Something like

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

但是,正如亚历山大所提到的,这绝对是重复的.您本可以编辑相同的问题.

But this is definitely a duplicate as mentioned by Alexander. you could have edited the same question.

这篇关于显示有和没有排序的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆