Java for loop with an ArrayList

Your code ist correct, though I would also advise you to make use of iterators:

import java.util.ArrayList;
import java.util.Arrays;


public class Main {

    public static void main(String[] args) throws Exception {

        ArrayList<String> contain = new ArrayList<String>(Arrays.asList("HPDH-1,001, Check-out date: 7/7/7",
                "JTI-1,001, Check-out date: 7/7/7"));

        String code = "JTI";

        // your loop
        for (int i = 0; i < contain.size(); i++) {
            if (contain.get(i).contains(code)) {
                System.out.println(contain.get(i));
            }
        }

        // my suggestion
        for (String s : contain) {
               if (s.contains(code)) {
                  System.out.println(s);
               }
        }
    }
}

Output:

JTI-1,001, Check-out date: 7/7/7

JTI-1,001, Check-out date: 7/7/7

If this output is not what you want, please add more information.


I think fundamentally the code is correct. I would check your inputs and make sure they're really what you think.

I would perhaps rewrite your loop as:

for (String s : contain) {
   if (s.contains(code)) {
      // found it
   }
}

to make use of the object iterators (the above assumes you have an ArrayList<String>). And perhaps rename contain. It's not very clear what this is.


The code is correct assuming List of strings. I have not modified any of your source code just to give you idea that it works fine.

    List<String> contain = new ArrayList<String>();
    contain.add("HPDH-1,001, Check-out date: 7/7/7");
    contain.add("JTI-1,001, Check-out date: 7/7/7");
    String code = "JTI-1 ";
    for (int i = 0; i < contain.size(); i++) {
        if (contain.get(i).contains(code.trim())) {<---Use trim it is possible that code may have extra space
            System.out.println(contain.get(i));
        }
    }