Home > database >  ArrayList size resetting to 1 in a for loop
ArrayList size resetting to 1 in a for loop

Time:11-09

I am trying to find the index of a value in a nested ArrayList, but I need to find the position of the first ArrayList. I am receiving an error when I run this code:

public int findCity(String city) {
  city = "\""   city   "\"";
  System.out.println(cityArray.size());
  for (List<String> value : cityArray) {
    String newCity = value.get(1); 
    if (newCity == city) return cityArray.indexOf(value);
  }
  return -1;
}

The problem happens in the line after the for loop:

String newCity = value.get(1);

It's telling me that index 1 is out of bounds for length 1. Any help is greatly appreciated!

I found the problem: I was using nextLine() to read the csv file, and it was creating a new array every time there was a space. This was a huge oversight on my part, but now I can start fixing the problem.

Once again, sorry for the inconvinience.

CodePudding user response:

You're mixing up cityArray.size() and cityArray.get(1).size(), which can be completely different.

(You are also comparing strings with ==, which is likely to cause disaster. Use .equals.)

CodePudding user response:

i think the problem is that you start counting from 1, but an ArrayList starts counting from 0. This is why the index is out of bounds.

You could try this:

String newCity = value.get(0);

CodePudding user response:

Below code can help you ,though I did not understand your problem.

public static void main(String[] args) {
        List<String> list1 = Arrays.asList(new String[]{"A","B"});
        List<String> list2 = Arrays.asList(new String[]{"Y","Z"});
        List<List<String>> cityArray = new ArrayList<>(2);
        cityArray.add(list1);
        cityArray.add(list2);
        System.out.println(findCity("Z", cityArray));
    }

    public static int findCity(String city, List<List<String>> cityArray) {
        System.out.println(cityArray.size());
        for (List<String> value : cityArray) {
            for(String newCity :value) { 
                if (newCity.equalsIgnoreCase(city)) {
                    return cityArray.indexOf(value);
                }
            }
        }
        return -1;
    }
  •  Tags:  
  • java
  • Related