0

Following is the program I wrote as an answer for the question -

"Now use ArrayList and the Integer wrapper class to store the values and initialize the elements by reading input from console using Scanner class.Extend the program to identify the n maximum values in the ArrayList."

import java.util.ArrayList;
import java.util.Scanner;    

public class ArraylistInput {
/**
 * @param args
 */
public static void main(String[] args) {

    ArrayList<Integer> val = new ArrayList<Integer>();
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the length of you Array List ");
    int nos = in.nextInt();
    // Recorrd the input numbers
    for (int i = 0 ; i < nos; i++)
    {
        System.out.println("Enter values for the ArrayList ");
        int Input = in.nextInt();
        val.add(Input);
    }

    // Display the arraylist
    for (int j = 0; j < nos; j++)
    {
        int x = val.get(j);
        System.out.println("Index " + (j+1) + ": " +  x);
    }
    System.out.println("How meny maximmum values do you want? ");
    int max =0; // initial max value
    int nmax = in.nextInt(); // number of maximum values
    int length = val.size(); // size of the arraylist

    // finding the maximum values in ascending order without sorting
    for (int h = 1; h <= nmax ; h++)
    {           
        for (int k=0;k < length; k++)
        {
            if (val.get (k) > max)
            {
                 max = val.get(k);
            }               
        }
        System.out.println ("maximmum = " + max);
        int z = val.indexOf(max); // removing the higest value after printing
        val.remove(z);
    }           
    }
}

Output and Error:

Enter the length of you Array List

3

Enter values for the ArrayList

12

Enter values for the ArrayList

45

Enter values for the ArrayList

8

Index 1: 12 Index 2: 45 Index 3: 8

How meny maximmum values do you want?

2

maximmum = 45

Exception in thread "main" maximmum = 45 java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(Unknown Source) at java.util.ArrayList.remove(Unknown Source) at ArraylistInput.main(ArraylistInput.java:46)

4 Answers 4

2

I would do the following:

Collections.sort(myList, Collections.reverseOrder());
List<Integer> maxn = myList.subList(0, n);
System.out.printf("The maximum %d values are: %s%n", n, maxn);
maxn.clear(); //This clears the sublist and removes its elements from the source list

That would give you a list with the maximun n elements in your list.

Sign up to request clarification or add additional context in comments.

2 Comments

I would prefer this too. But keep in mind that subList() returns a view. Any changes to myList will reflect in maxn.
@nansen Then add the sublist to another list: List<Integer> maxn=new ArrayList<>(myInts.subList(0,n)).
0

You only have a single ArrayList you don't need the nested for loop to find the maximum:

int max = Integer.MIN_VALUE;

for(int i = 0; i < list.size(); i++)
{
   current = list.get(i);
   if(current > max)
      max = current;
} 

The nested for loop when you are searching for the maximum tries to access a value in your list that doesn't exist, which is why you are receiving this error.

2 Comments

I believe the question is about getting the n maximun elements, not just one.
pretty simple to adjust this to get the n max
0

Your max is never getting assigned and then you are trying to remove a non-existing element from the arraylist. Set max to some value that cannot occur in the list and then check whether it ever got assigned in the loop.

Comments

0

When you remove an element from the list with:

val.remove(z);

You change the size of the list but you don't update your length variable. This causes you to try to access indices beyond the size of the array, resulting in a java.lang.ArrayIndexOutOfBoundsException.

Also, consider saving both the index of the max value and the max value itself. Then, when you go to remove the value, you can use ArrayList.remove() directly without searching the whole list again for the max index (which is what ArrayList.indexOf() will do).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.