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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With