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.

Answer from Brian Agnew on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_howto_loop_through_arraylist.asp
Java How To Loop Through an ArrayList
How Tos Add Two Numbers Swap Two ... Number ArrayList Loop HashMap Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String ...
Discussions

For-each loop ArrayList
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List. More on reddit.com
🌐 r/learnjava
6
11
April 4, 2023
Java: Printing an ArrayList in one line with foreach - removing last comma
But I'd like to use a foreach loop why? there's not an easy way afaik you could use a string builder by appending each item to the builder followed by a comma, then pop the trailing comma off and print the built string. not 100% aware of how System.out.print buffers its output, but my using a string builder you could ensure that it's just a singular write to the console edit: or just use String.join More on reddit.com
🌐 r/learnprogramming
12
2
February 4, 2021
Java while loop to find index of elements in ArrayList
ArrayList.indexOf(Object o) will always return the index of the first occurrence of the given object, so what you observe is happening by design; to get the indices of the others, you would have to remove the item from the list once you find it so that when you call indexOf again, the next occurrence is seen. Alternatively, you could scan through the list and compare elements directly instead of using indexOf. That way, you wouldn't have to modify the list at all, since you'd simply be looking at each item and comparing with a reference value. More on reddit.com
🌐 r/learnprogramming
13
1
May 4, 2017
Iterating through an arrayList of objects
Well an array list is like an array except it's endless. An array can ONLY hold a limited amount of items you tell it to whereas an array list can hold as many items and constantly grows to hold more items. With that said, you can get stuff from (for example): for (int I = 0; I < arraylist.size(); I++) { if (arraylist.get(i).getId() == 1) { sysout("found!"); } } when you say arraylist.get(i), it's an Employee object- meaning it has all the employee methods (accessors/mutators aka getters/setters). Using an enhanced for each loop is the same thing except no need to say arraylist.get(i) anymore since emp is the same as arraylist.get(i) More on reddit.com
🌐 r/javahelp
6
1
November 7, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterating-arraylists-java
Iterating over ArrayLists in Java - GeeksforGeeks
Method 1: Using a for loop · Java · import java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Creating and initializing the ArrayList // Declaring object of integer type List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); // Iterating using for loop for (int i = 0; i < numbers.size(); i++) // Printing and display the elements in ArrayList System.out.print(numbers.get(i) + " "); } } Output ·
Published   January 19, 2026
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › how-to-loop-arraylist-in-java
How to loop ArrayList in Java
One of the limitations with for-each loop is that you cannot remove an element while iterating. An Iterator provides a way to iterate a collection, and it allows you to remove an element while iterating. import java.util.ArrayList; import java.util.Iterator; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Chaitanya"); names.add("Rahul"); names.add("Aditya"); Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit8-ArrayList › topic-8-3-arraylist-loops.html
8.3. Traversing ArrayLists with Loops — CS Java
You can also use a while or for loop to process list elements using the index. The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an ...
🌐
Programiz
programiz.com › java-programming › examples › iterate-over-arraylist
Java Program to Iterate over an ArrayList
Here, we have used the for-each loop to iterate over the ArrayList and print each element. import java.util.ArrayList; import java.util.ListIterator; class Main { public static void main(String[] args) { // Creating an ArrayList ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(3); numbers.add(2); System.out.println("ArrayList: " + numbers); // Creating an instance of ListIterator ListIterator<Integer> iterate = numbers.listIterator(); System.out.println("Iterating over ArrayList:"); while(iterate.hasNext()) { System.out.print(iterate.next() + ", "); } } }
🌐
Reddit
reddit.com › r/learnjava › for-each loop arraylist
r/learnjava on Reddit: For-each loop ArrayList
April 4, 2023 -

I am in the third part of a MOOC course on Java. And I'm a little confused about the ambiguity of using the For-each loop to enumerate a list.

Consider the following list as an example

ArrayList<Integer> list = new ArrayList<>();

The examples and answers present two implementations:

for (Integer val: list) {

//do something

}

for (int val: list) {

//do something

}

But it is not explained how one differs from the other and when one or the other variant should be used. Please tell me the difference between the two.

Top answer
1 of 3
13
Java has something called autoboxing and unboxing . Integer is an object. int is a primitive type. An Integer object can be unboxed into a int. And an int can be autoboxed into a Integer. In the examples above the List contains Integer objects. The difference is: In the first, val is a reference to the Integer object in the List. In the second, val is a primitive value that was unboxed from the Integer object in the List.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › different ways to iterate an arraylist
Different Ways to Iterate an ArrayList
January 12, 2023 - ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") ); for(String name : namesList) { System.out.println(name); } Java program to iterate through an ArrayList of objects using ListIterator interface. ArrayList namesList = new ArrayList(Arrays.asList( “alex”, “brian”, “charles”) ); ListIterator listItr = namesList.listIterator(); while(listItr.hasNext()) { System.out.println(listItr.next()); } Java program to iterate through an ArrayList of objects using a while loop.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 03 › how-to-loop-arraylist-in-java-code.html
5 Ways to Loop or Iterate over ArrayList in Java?
We can iterate on Java ArrayList using foreach loop introduced in Java 5, by far most clean method until you don't need to remove elements from ArrayList in that case you must use Java Iterator for looping or iterating over ArrayList.
🌐
CodeGym
codegym.cc › java blog › java collections › enhanced for loop in java
Enhanced for loop in Java
February 13, 2025 - If you're a Java developer, you've probably come across a situation where you need to iterate over an array or a collection. In the past, this required writing a lot of boilerplate code to set up a loop and iterate over the elements. However, Java has introduced an enhanced for loop, which makes iterating over collections and arrays much easier.
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit7-ArrayList › topic-7-3-arraylist-loops.html
7.3. Traversing ArrayLists with Loops — CSAwesome v1
You can also use a while loop or ... of using the index operator [] to access elements, you use the get(index) method to get the value at the index and set(index,value) to set the element at an index to a new value....
🌐
IONOS
ionos.com › digital guide › websites › web development › java for-each loop
How to use for-each loops in Java - IONOS
November 3, 2023 - The for-each loop is used in many scenarios where Java de­vel­op­ers need to work with arrays. For example, a common use is to output or search for specific elements of an array. The for-each loop can likewise be used to iterate through elements in a list im­ple­ment­ed as an ArrayList.
🌐
Vultr Docs
docs.vultr.com › java › examples › iterate-over-an-arraylist
Java Program to Iterate over an ArrayList | Vultr Docs
November 25, 2024 - The enhanced for loop directly accesses each element in the ArrayList colors and prints it. This loop is more readable and eliminates the need to manually control the index. Obtain an iterator from the ArrayList, and use it to iterate through ...
🌐
Mkyong
mkyong.com › home › java › how to loop arraylist in java
How to loop ArrayList in Java - Mkyong.com
August 29, 2012 - package com.mkyong.core; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListLoopingExample { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("Text 1"); list.add("Text 2"); list.add("Text 3"); System.out.println("#1 normal for loop"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("#2 advance for loop"); for (String temp : list) { System.out.println(temp); } System.out.println("#3 while loop"); int j = 0; while (list.size() > j) { System.out.println(list.get(j)); j++; } System.out.println("#4 iterator"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
🌐
TutorialsPoint
tutorialspoint.com › iterate-through-arraylist-in-java
Iterate through ArrayList in Java
July 28, 2025 - Iterating through ArrayList using for loop: 1 2 3 4 5 · Another way to iterate through an ArrayList is by using a while loop. We will use an index variable to keep track of the current position in the ArrayList. In the below example, we will create an ArrayList of Integer type and then iterate over it using a while loop: import java.util.ArrayList; import java.util.List; public class IterateArrayList { public static void main(String[] args) { List<Integer> arrayList = new ArrayList<>(); arrayList.add(10); arrayList.add(20); arrayList.add(30); arrayList.add(40); System.out.println("Iterating through ArrayList using while loop:"); int i = 0; while (i < arrayList.size()) { System.out.print(arrayList.get(i) + " "); i++; } } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings. ... // Java program to demonstrate the use of forEach() // with an ArrayList of Strings import java.util.ArrayList; public class GFG { public ...
🌐
Java67
java67.com › 2012 › 08 › how-to-traverse-iterate-or-loop-ArrayList-in-java-example-tutorial.html
How to traverse iterate or loop ArrayList in Java | Java67
In summary use advance for loop to loop over ArrayList in Java, its short, clean and fast but if you need to remove elements while looping use Iterator to avoid ConcurrentModificationException.
🌐
Codecademy
codecademy.com › docs › java › arraylist › .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - The .forEach() method provides a concise way to iterate through all elements in an ArrayList and apply the same operation to each element. It utilizes functional programming concepts by accepting a Consumer function that defines what action ...
🌐
Medium
medium.com › @YodgorbekKomilo › day-12-for-each-loop-arraylist-in-java-7802d97b799c
Day 12 — For-each Loop & ArrayList in Java | by Yodgorbek Komilov | Medium
December 24, 2025 - When you want to iterate over elements of an array or a collection, the traditional for loop with an index works fine—but Java provides a cleaner way: the for-each loop. for (datatype variable : arrayOrCollection) { // code to execute for ...