I have an interesting problem on how to insert any number into an ordered ArrayList. Lets say the user enters [12,34,37,60,89]; the method addListElement() should traverse the array to find the index where the new element will go.
The user enters the number 50, the new array should be [12,34,37,50,60,89]. I used a for loop to traverse the ArrayList, but I’m not sure about my if() statement.
public void addListElement() {
System.out.println("Add number to arrayList");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int loc = 0;
for (int i = 0; i < aryList.size(); i++) {
if (number > 0 && i < loc) {
loc++;
}
}
aryList.add(loc, number);
System.out.println(aryList.toString());
}
this should work too. Since the list is already in ascending order, when ever you find the number in list bigger than the current one, insert the new number one index before this number in arrayList..