0
 Vertex [] vertices = new Vertex[n]; 
int [] numbers = new int[n*2]; 
AdjacencyList[] all = new AdjacencyList [n+1];

for (Vertex v : vertices)
{ 
  System.out.println(v.value); 
  AdjacencyList a = new AdjacencyList(v); 
  for (int i = 0; i < n; i += 2)
  {     
      if (numbers[i] == v.value){
         a.connected[i] = vertices[i+1];//array index out of bounds exception:19
      else { a.connected[i] = v; }       
  }
  all[0] = a; //add the finished adjacency list to the array

}

with n = 19 can I'm getting an index out of bounds error at the point indicated in the code. I'm not sure where I'm going wrong, as everything is still within the bounds of 19

vertices = list of Vertex [1-19], numbers is a flattened array of edges

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
MScoder5
  • 3
  • 4
  • You call `vertex[19+1]`. (the 20th index and thus out of bounds) – GBlodgett Jun 03 '18 at 20:17
  • 1
    Possible duplicate of [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – Pavneet_Singh Jun 03 '18 at 20:18

2 Answers2

0

In the line:

a.connected[i] = vertices[i+1];

You call the index i+1. This will result in an index out of bounds exception. (In your example of when n equals 19: The valid index's will be [0-18]. Your loop will go from 0-18. But in the line it will then add one to it. 18+1 = 19, which is an invalid index) In your loop change the condition to:

for (int i = 0; i<n-1; i+=2){

To make sure it will not go out of bounds when you add one.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • @MScoder5 You're welcome! If an answer solved your problem don't forget to accept the answer (I don't mean this answer specifically. Just for the future) – GBlodgett Jun 03 '18 at 21:04
0

Your array has length, n=19, meaning index [0-18] and i is incremented by 2.

So when i = 18,

 a.connected[i] = vertices[i+1];

tries to access vertices[19] which is not existent. Hence ArrayOutOfBoundException. Hope this helps.

Antariksh
  • 508
  • 8
  • 17