我如何不使用Collections.sort方法按字母顺序排列此ArrayList?

问题描述 投票:1回答:2

这是我正在做的一项有趣的学校作业。在本次分配中,我应该将单词插入ArrayList,然后手动停止ArrayList,然后程序应将其按字母顺序排列。但是问题是,每个教程都告诉我使用Collections.sort方法之类的东西,但是我们还没有在课堂上学到它,所以显然我们不是要使用它。此外,此任务的挑战是对1个ArrayList中的所有内容进行排序,而不是从ArrayList中获取单词,将单词按字母顺序排列,然后将按字母顺序排列的单词插入第二个ArrayList中。有人可以帮我解决这个问题吗?我没有在字母顺序部分中写任何东西,因为我不知道从哪里开始。谢谢。

import java.util.*;

public class LexiHeaven {

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a word into the Array (enter stop if you want to stop):");
        String w = sc.nextLine();

        while (!w.equals("stop")) {
            words.add(w);
            System.out.println("Please enter a word into the Array (enter stop if you want to stop):");
            w = sc.nextLine();
        }

        System.out.println(words);
        System.out.println("Alphabetize the ArrayList:");

        // this is where the code for alphabetizing should go

        String temp;
        for (int i = 0; i < words.size(); i++) {
            for (int j = i + 1; j < words.size(); j++) {
                temp=words.get(i);
                words.set(i, temp);
                words.set(i,words.get(j));
                words.set(j, temp);
                }
            }
        }
    }
}
java string arraylist swap
2个回答
0
投票

似乎我无法在评论中很好地解释自己,所以我将让我的代码为我代言。


0
投票

让我们看看您编写的代码:

© www.soinside.com 2019 - 2024. All rights reserved.