-2

So I have an android application and frequent forced close. Why on my logcat the following Method often causes errors?

static void solveTSP(int[][] valuesMatrix) {
        shortestDistance = Integer.MAX_VALUE;
        longestDistance = Integer.MIN_VALUE;
        shortestPath = null;

        int totalPlaces = valuesMatrix.length;
        ArrayList<Integer> places = new ArrayList<>();
        for(int i=0; i<totalPlaces; i++){
            places.add(i);
        }
            int startPlace = places.get(0);// in logcat, this line is the  cause of the Index error Out of Bounds Exception: Invalid index 0, size is 0. How does that happen?

        int currentDistance = 0;
        bruteForceSearch(valuesMatrix, places, startPlace,   currentDistance);
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • put a break point on your for loop... check if your arratList is actually being populated or not – Milan Desai May 24 '19 at 09:41
  • Do you understand the error message? – Thorbjørn Ravn Andersen May 24 '19 at 09:41
  • totalPlaces is 0, so id doesn't go inside for loop, places is empty list and it throws error when you try to lookup first element of empty list – miljon May 24 '19 at 09:41
  • 1
    Which parameter are you passing to the method? I guess an empty array, so `valuesMatrix.length` is 0, the for loop is not executed, so nothing is added to `places` and `get(0)` is throwing. – burm87 May 24 '19 at 09:41
  • It clearly mentioned in error that valuesMatrix size is zero, so when you try to get oth element, it throws same exception. Other thing is, you are just storing 0 to valuematrix length in places, startplace will always be zero(0). – Chirag Shah May 24 '19 at 10:09

3 Answers3

1

If valuesMatrix is empty, then places will have a length of 0 and no values inside, hence the error when you try to do places.get(0).

RoadEx
  • 543
  • 2
  • 12
1

1) Please try to log your valuematrix length, because it is clearly mentioned in error that valuesMatrix size is zero, so your palces list is also empty. And hence, when you try to get 0th element, it throws same exception.

2) Other thing is, you are just storing 0 to valuematrix length in places list, so, startplace will have value always zero(0).

Chirag Shah
  • 353
  • 1
  • 13
1

The length of valuesMatrix is definately 0 which is getting assigned to totalPlaces. So your 'for' loop does not run and nothing gets added to your ArrayList 'places'. So when you are trying to get value from its zeroth position you are getting an exception. Check the size of places variable, if it is grater than zero then only proceed with further statements as below:

for(int i=0; i<totalPlaces; i++){
        places.add(i);
    }
if (places.size() > 0) {
int startPlace = places.get(0);
}