How do i iterate through this arraylist ?


I'm relatively new to programming. I'm trying to teach myself Java, and I'm messing around with ArrayLists. How do I go about printing each of these strings individually? Right now, I have it where it prints each list, but I want to be able to work with each string individually. Like if I wanted to print out the length of each string using a for loop how would I do that? I tried doing the standard for loop, but I couldn't figure out what to put for the termination requirement. I tried i < 2 since test[3] is length 2, but that gave an out of bounds error since the other test lists only have one element.
public static void main(String[] args)
{
  int arrlen = 4;
  ArrayList[] test = new ArrayList[arrlen];

  for(int i=0; i<arrlen; i++)
  {
    test[i] = new ArrayList<String>();
  }

  test[0].add("zero");
  test[1].add("one");
  test[2].add("two");
  test[3].add("three");
  test[3].add("second three");


  for(ArrayList i : test)
  {
    System.out.println(i);
  }

}

Hey Andrew Lygin ,
For Solving Your Problem I have to use a simple get method for finding all elements of ArrayList inside for loop and by using length method  find length of elements of ArrayList .
ArrayList<String> test=new ArrayList<String>();
      test.add("one");
      test.add("two");
      test.add("three");
      test.add("four");
      for(int i=0;i<test.size();i++){
        System.out.println(test.get(i).length());
      }

      System.out.println(test);  

Comments

Popular posts from this blog

Secure Database Connectivity in node.js with mysql

Export data from mysql db to csv file using java

API (Application Programming Interface)