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

• August 25th, 2013, 05:41 AM
ojonugwa
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?
• August 25th, 2013, 07:05 AM
GregBrannon
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.
• August 25th, 2013, 08:23 PM
Junky
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.
• August 26th, 2013, 04:41 PM
syedbhai
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.