Finding the index of the maximum number in an ArrayList and removing the number that occupies that index

Here is my code which works fine

Code :

public class Arrays {
public static void main (String[]args) {
int maxNum= 0;
int minNum = 100;
int position=0;
ArrayList <Integer> numbers = new ArrayList<Integer>();
int i;
for (i=0; i<5;i++) {
numbers.add((int)(Math.random()*10)+1);
}
Collections.sort(numbers);
System.out.println(numbers);
try {
for (i=0;i<numbers.size();i++){
if (numbers.get(i) > maxNum) {
position=i;
maxNum = numbers.get(i);
}
}
numbers.remove(position); //removes the index that contains the maximum number
System.out.println("Maximum number: " + maxNum);
System.out.println("Found max at index " + position);
System.out.println(numbers);
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}}

The problem is, sometimes random numbers containing two maximum numbers such as 4, 10, 2, 10,6 is generated.With what i have, only one of the 10s is removed.How do i make sure both are removed?

Re: Finding the index of the maximum number in an ArrayList and removing the number that occupies that index

If you're still trying to generate unique random numbers, I suggest you review my response to your other topic. A Set would be a much more convenient collection for ensuring uniqueness. That's what it's for. You're just reinventing that with what you're trying to do here.

Re: Finding the index of the maximum number in an ArrayList and removing the number that occupies that index

If you have multiple values as the maximum then find the maximum value instead of the index. Then iterate over the List again and delete all instances of that value.

Re: Finding the index of the maximum number in an ArrayList and removing the number that occupies that index

Hello.

I have an alternate solution. No matter whether you have duplicated values or not. It should work for both the scenarios.

You have already sorted your collection in ascending order.

Get the last value, cache it and delete it.

Ex: int n=list.get(list.size()-1); list.remove(list.size()-1);

Then check if the last value in the remaining list is again same as n. If yes repeat the above step. Do it until the last element of the remaining list is different than what was deleted earlier.

Syed.