[英]How do I sort my ArrayList in alphabetical order and have it used with a setText method?
這就是我所擁有的
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
Collections.sort(cdList, String.CASE_INSENSITIVE_ORDER);
System.out.println(cdList);
bigBox.setText("Original Order\n**************\n");
for (int i = 0; i < cdList.size(); i++) {
bigBox.setText(bigBox.getText()+""+cdList.get(i)+"\n");
}
bigBox.setText(bigBox.getText()+"\n\nSorted Order\n************\n");
Collections.sort(cdList);
for (int j = 0; j < cdList.size(); j++) {
bigBox.setText(bigBox.getText()+""+);
}
我希望按原始順序和字母順序輸出4個示例。 我究竟做錯了什么?
您僅將一個元素(字符串)添加到列表中,即串聯字符串。
改變這個
ArrayList <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
至
List <String> cdList = new ArrayList<String>();
Collections.addAll(cdList, "ExampleA","ExampleB","ExampleC","ExampleD");
為了顯示您應該使用append而不是setText
。
例:
bigBox.append("Original Order\n**************\n");
for (String s : cdList) {
bigBox.append(s);
bigBox.append("\n");
}
我假設您的元素是字符串"ExampleA"
, "ExampleB"
, "ExampleC"
和"ExampleD"
。 如果是這種情況,則當前在調用Collections.addAll()
正在做的就是將它們作為一個長字符串添加到cdList中。 當在字符串上使用+
運算符時,會將它們追加。 您可能希望它用逗號分隔它們,而不是這樣:
Collections.addAll(cdList, "ExampleA\n"+"ExampleB\n"+"ExampleC\n"+"ExampleD");
你有:
Collections.addAll(cdList, "ExampleA\n", "ExampleB\n", "ExampleC\n", "ExampleD");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.