-4

This error keeps occurring Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 131071

I'm trying to create an array of 131071 integers with no duplicates.

public class array {
    public static void main(String[] args) {
        populateArray();
    }
    public static void populateArray(){
        int [] numbers = new int [131071];
        int k = 0;
        Random r = new Random();        
        for (int i = 0; i < 131070 ; i++) {
            int random=r.nextInt(13071)+1;
            for (int h = 0; h <= i; h++) {
                if (random != numbers[h]) {
                    numbers [k] = random;
                    k=k+1;    
                }
            }
            }                             
        for (int j = 0; j < 131071; j++) {
            Arrays.sort(numbers);
            System.out.println(numbers[j]);

        }
                }

        }
Ryan.Java
  • 1
  • 1
  • It is **impossible** to create an array of 131071 non-duplicate integers in the range 1 to 13071 (inclusive). Did you mean to call `nextInt(131071)`? – Andreas Feb 18 '19 at 21:57
  • 1
    It seems you want an array of the numbers 1 - 131071 (inclusive) in random order. To do that, fill the array with the numbers, then **shuffle it**. Do a web search for [`java shuffle array`](https://www.google.com/search?q=java+shuffle+array) if you need to find out how to do that. – Andreas Feb 18 '19 at 21:59
  • You may want to learn [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Turing85 Feb 18 '19 at 22:11

1 Answers1

0

The exception is being cause by the fact that you have two nested for loops, and you're incrementing k in the inner loop without ever resetting it, so it goes higher than 131071.

However, this code won't do what you want even if you fix that. You need to take a step back and re-think how, specifically, you want to detect duplicates.

Also, I'd suggest against hard-coding the same integer value in multiple places. You have a typo in there that makes you code non-functional, and which could have been avoided if you assigned the int to a variable, and used that variable in multiple places.

Jordan
  • 2,168
  • 7
  • 15
  • I would suggest a BitSet to track duplicates, e.g `if (!bs.get(random)){ //add random at next array position, then...bs.set(random);}` – SteveR Feb 18 '19 at 22:54