Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop with an ArrayList

Here is the contents of my ArrayList contain

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

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

My code:

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

The thing is my variable code was String "JTI-1" Why isn't it giving me the JTI-1 output? I am trying to get it to display the value of the variable code. I want to remove the contain.get(i) if it would just give me the one I typed in.

like image 926
DDDD Avatar asked Oct 19 '12 08:10

DDDD


People also ask

Can we use for loop for ArrayList in Java?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .

Can you loop through a list in Java?

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.


2 Answers

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.

like image 88
Brian Agnew Avatar answered Sep 21 '22 01:09

Brian Agnew


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));
        }
    }
like image 27
Amit Deshpande Avatar answered Sep 22 '22 01:09

Amit Deshpande