2

I'm trying to initialize an array and insert some values into it in Java, but I get out of bounds exception. This is the code

int xPoints[] = new int[]{};
int i = 0;
for(Edge e : myVectorOfEdges){
    xPoints[i] = e.start;
    i++;

}

I must use this type of data structure, because I am working with polygons which accept only int[] type.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Keselme
  • 3,779
  • 7
  • 36
  • 68

3 Answers3

2

You have initialized xPoints as an empty array, so any attempt to access one of its (non-existent) elements will result in an ArrayIndexOutOfBoundsException. Instead, you should initialize it to the same size as myVectorOfEdges which you are iterating:

int xPoints[] = new int[myVectorOfEdges.length];
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • The problem with this implementation is the length on the vector is much larger than I actually need to use, because it contains all edges from my input file, while I need to iterate through it and look for polygons, and than create xPoints[] for each polygon I find – Keselme May 08 '16 at 21:06
1
int xPoints[] = new int[myVectorOfEdges.length];
    int i = 0;
    for(Edge e : myVectorOfEdges){
        xPoints[i] = e.start;
        i++;

    }
Oussema Aroua
  • 5,225
  • 1
  • 24
  • 44
0

Just use the slow version:

    int[] xPoints = myVectorOfEdges.stream().mapToInt(e -> e.start).toArray();
Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40