Search code examples
javaarraylistvariable-length

Finding length of all values in an ArrayList


For a program I'm attempting to have a nested for loop repeat along the lines of this:

for(int i = 0;i < ArrayList.size();i++){
    for(int x = 0;x <ArrayList.get(i).length();x++){
        //stuff
    }
}

Essentially I want to repeat a for loop for every character in every index of an ArrayList but this solution doesn't seem to work. Any help appreciated!

Edit: the arraylist will only contain strings in my case


Solution

  • Try using a For Each Loop such that:

    int sumLength = 0;
    ArrayList<String> r = new ArrayList<String>();
    for(String s : r)
    {
     sumLength += s.length();
    }
    return sumLength;
    

    That will give you the sum of all the lengths in your ArrayList