简体   繁体   中英

Manually sorting an ArrayList of strings alphabetically in Java

I am trying to reorder an ArrayList alphabetically for an assignment. I am not allowed to use any methods for automatically sorting, it has to be done manually. This is the code I tried, but it does not even run. I appreciate any input on this.

import java.util.ArrayList;

public class SortArrayList {
    public static void main(String[] args) {
        ArrayList<String> values = new ArrayList<String>();
        public static void main(String[] args) {
        ArrayList<String> values = new ArrayList<String>();
        values.add("car");
        values.add("bear");
        values.add("apple");
        values.add("xray");
        sort(values);
        for (int i = 0; i < values.size(); i++)
            System.out.println(values.get(i));
    }

    public static void sort(ArrayList<String> x) {
        String temp;
        for (int i = 0; i < x.size() - 1; i++) {
            for (int j = i + 1; j < x.size(); j++) {
                if (x.get(i).compareToIgnoreCase(x.get(j)) > 0) {
                    temp = x.get(i);
                    x.add(i,x.get(j));
                    x.add(j,temp); 

                }
            }
        }
    }
}

The lines

x.add(i,x.get(j));
x.add(j,temp);

are adding more elements to the ArrayList. You should change them to

x.set(i, x.get(j));
x.set(j, temp);

so that it replaces the elements at those positions.

除非对你的问题复制它时多次调用public static void main(String [] args)是一个拼写错误,否则这会导致运行程序时出现问题,因为它不知道从哪里开始

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM