Java works a little bit different than many other languages. What o is in the first example is simply a reference to the object.

When you say o = new MyObject(), it creates a new Object of type MyObject and references o to that object, whereas before o referenced objects[index].

That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].

Image: (my terrible paint skills :D)

Explanation: This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you're looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.

o does not reference A1 or B1, but C1 or C2. When you say new ..., it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.

Let me know if I can clear things up a little.

Answer from Ryan Amos on Stack Overflow
Top answer
1 of 7
15

Java works a little bit different than many other languages. What o is in the first example is simply a reference to the object.

When you say o = new MyObject(), it creates a new Object of type MyObject and references o to that object, whereas before o referenced objects[index].

That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].

Image: (my terrible paint skills :D)

Explanation: This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you're looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.

o does not reference A1 or B1, but C1 or C2. When you say new ..., it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.

Let me know if I can clear things up a little.

2 of 7
10

The short answer: yes, there is something like a copy going on.

The long answer: The Java foreach loop you posted is syntactic sugar for

MyObject objects[] = new MyObject[6];

Iterator<MyObject> it = objects.iterator();
while (it.hasNext()) {
   MyObject o = it.next();
   // The previous three lines were from the foreach loop

   // Your code inside the foreach loop
   o = new MyObject();
}

As the desugared version shows, setting a reference equal to something inside a foreach loop does not change the contents of the array.

🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
June 10, 2017 - The for-each loop in Java (introduced in Java 5) provides a simple, readable way to iterate over arrays and collections without using indexes.
Discussions

Java objects For Each Loops
eric Crawford is having issues with: OK....Hello! I've been learning and im really trying to get syntax and terminology of Java down. That being said I keep wondering if... More on teamtreehouse.com
🌐 teamtreehouse.com
2
October 2, 2015
Java Object Array Foreach Method Access - Stack Overflow
After developing in PHP for a long time I have decided to step into Java. Comfortable in OOP methodology and all that, I'm trying to start off at that point within java, but I'm getting hung up on More on stackoverflow.com
🌐 stackoverflow.com
Java library for 3d object visualisation

With this I would say you would want to use OpenGL. I'd recommend something like LibGDX. It uses LWJGL in the background but is less low-level making it easier for you. Although seeming as your example is using C# in Unity maybe you could use that? It could be a lot easier using a game engine like Unity.

More on reddit.com
🌐 r/AskProgramming
1
2
March 30, 2018
Obba: A Java Object Handler for Excel.
267k members in the java community. News, Technical discussions, research papers and assorted things of interest related to the Java programming … More on reddit.com
🌐 r/java
🌐
Tutorialspoint
tutorialspoint.com › java › java_foreach_loop.htm
Java - for each Loop
Then using foreach loop, each name is printed. import java.util.Arrays; import java.util.List; public class Test { public static void main(String args[]) { List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy"); for( String name : names ) { System.out.print( name ); System.out.print(","); } } } ... In this example, we're showing the use of a foreach loop to print contents of an array of Student Object.
🌐
Google Groups
groups.google.com › g › tasker › c › FWtOVgFSPLU
For each Java object in Java array
GetSyncAdapters2 (80) A1: Java Function [ Return:sat Class Or Object:ContentResolver Function:getSyncAdapterTypes {SyncAdapterType[]} () Param: Param: Param: Param: Param: Param: Param: Continue Task After Error:On ] A2: For [ Variable:%var Items:sat ] A3: Java Function [ Return:adap Class Or Object:(SyncAdapterType) %var Function:assign {SyncAdapterType} () Param: Param: Param: Param: Param: Param: Param: ] A4: Java Function [ Return:%str Class Or Object:adap Function:toString {String} () Param: Param: Param: Param: Param: Param: Param: ] A5: Flash [ Text:%str Long:Off ] A6: End For A7: [X] HTML Popup [ Code:%sat(#)
🌐
Programiz
programiz.com › java-programming › enhanced-for-loop
Java for-each Loop (With Examples)
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
Top answer
1 of 2
1
Hey Eric! Awesome to here you came to these forums for clarification on this! I'll try my best to help out ;) So, where we have this line: java public int getTileCount(char letter) { char is the data type and letter is the name of the variable. You are completely right that we could rename letter to anything we want and the code will still work - it's just easy to refer to letter as it is, so we know what it's doing. If you wanted to, you could call it myLetter, theBestLetter or anything you want! match would also work! Now for our for loop: java for (char tile :mHand.toCharArray()) { The : is a funny one. I like to think of it as the word in. So, I would read this out as for every char which we'll refer to as tile in the mHand char array.... Now, toCharArray() is very good terminology and here's a few pieces of terminology we use in methods: to - Generally used for conversion, changing one object to a different object. get - We call these methods getters, when we want to get something (This could be a class, a String, boolean, you name it!) set - We call these methods setters, when we want to set something (e.g: We may have a name variable stored in an AboutMe class, and we can set the name from any other class with this method). Now, there's no "law" on naming your methods like this, just like there's no law in not writing in camel-case. Instead, it's convention that we do so and when working in a team on the same project, everyone follows these conventions to ensure consistency. Your code's not going to break by writing differently, it's just many people would frown upon not following these conventions. Things like the : and = are required as part of the Java syntax. We can't ever write these differently, it just won't work! We'll get an error in our code if we try to. As you write more in Java, you will realise what you can and can't change. Like right now, you are probably already aware that you must use an = to define a variable, we can't use anything else as it's just against the syntax! Hopefully this should explain these concepts for you but if you need anything explained a bit more, give me a shout and I'll be sure to help out :)
2 of 2
1
I'm no Java expert, but I'll do my best to help clarify. In your first example, letter is an argument name. You can use any Java-valid variable name for this, it doesn't have to be letter. Remember that if you change the argument name, you also need to change the reference to it in your if expression. java // When passing arguments to a function, you can call the variable whatever you want. public int exampleFunction(int someArgumentName) { } The second part is a bit trickier because I'm not super familiar with the Java language. I believe that the colon is a necessary syntax that's part of the Java for each constructor. You're basically saying for each thing in things execute some block of code. The toCharArray() is a method included in Java that converts a string to a new array of characters. So if your string is "Hello" you would get back ["H", "e", "l", "l", "o"] if you called this method on it. In this case, you're using it so that you can iterate over the characters and check to see if the specified tile is in a given hand. java // For each character tile in the array of characters obtained from String mHand, check to see if it matches. for (char tile :mHand.toCharArray()) { } Hopefully that helps. Please let me know if anything is still unclear, and I'll do my best to help you work it out. Happy coding! :)
🌐
iO Flood
ioflood.com › blog › for-each-loop-java
For-each Loops in Java | An Enhanced For-Loop Guide
February 20, 2024 - In this example, we have a Person class with a name and age field, and a toString() method that returns a string representation of the object. We then create a list of Person objects and use a for-each loop to iterate over the list and print each Person object. While the for-each loop is a powerful tool for iterating over collections in Java, it’s not the only tool available.
Find elsewhere
🌐
Runestone Academy
runestone.academy › ns › books › published › apcsareview › ArrayBasics › aForEach.html
8.2. Looping with the For-Each Loop — AP CSA Java Review - Obsolete
For-each loops access all of an array's elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly. You can use the Java Visualizer to step through this code by clicking on the following link link2. Notice that we have to create an object ...
🌐
Coderanch
coderanch.com › t › 533475 › java › pass-reference-Java-loop
pass by reference in Java [for each loop] (Java in General forum at Coderanch)
April 6, 2011 - You doubtless already know there ... in Java™. In a for-each loop, it is more confusing. The loop iterates the collection, copying each element into a temporary reference. If you assign to that temporary variable, it alters the copy, but has no effect on the original in the collection, array or whatever. ... Sonx Nkuks wrote:Does the object point to the ...
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):
Top answer
1 of 2
9

You have a very strange architecture here my friend. You shouldn't be using generic Objects everywhere, but the actual types. First thing:

public Object getAllInventoryItems() {
    //return InventoryItems;
     return this.InventoryItems.toArray();
}

Why not just return the List itself?

public List<Item> getAllInventoryItems() {
     return this.InventoryItems;
}

Also change this:

List<Item> InventoryItems = new ArrayList<Item>();

and this:

public void setInventoryItems(Item inventoryItems) {
     this.InventoryItems.add(inventoryItems);
}

Now iterating the List is smooth sailing:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    List<Item> InvetoryItems;

    Inventory inv = new Inventory();
    inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
    InvetoryItems = inv.getAllInventoryItems();

    for(Item item : InvetoryItems){
           System.out.println(item.getItemName());
    }

    System.out.println("Done");
}

Btw, I changed Items to Item out of habit. A class name should indicate a single entity so by convention it's singular.

Now don't take this the wrong way, but you may have got off on the wrong foot with Java, so I highly recommend this reading: http://www.mindview.net/Books/TIJ/ This worked for me when I was starting with Java, maybe others can suggest some good sources as well.

2 of 2
2

Ok, two things. One is that Tudor is absolutely right, it's best to use the classes you're expecting directly, not Objects, and stylistically his points are accurate too.

Two is that if you really have to use a list of object, you'll need to cast back from object to whatever type it is that you're expecting to receive.

List<Object> list = inv.getAllInventoryItems();
for (Object item : list){
    System.out.println((Items) item).getItemName();
}

However, I wouldn't recommend doing this as it effectively takes what should be a compile-time error and makes it a RunTime error (if the class cannot be cast).

🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-iterate-through-collection-objects-in-java
How to Iterate through Collection Objects in Java - GeeksforGeeks
This approach is applicable only for indexed collections like List, ArrayList, Vector. ... import java.util.*; class GFG{ public static void main(String[] args) { // Declaring the Vector Vector<String> gfg = new Vector<>(); // Adding elements gfg.add("Abhishek Rout"); gfg.add("Vaibhav Kamble"); gfg.add("Anupam Kumar"); // Iterating using simple for loop for (int i = 0; i < gfg.size(); i++) { System.out.println("Name " + (i + 1) + ": " + gfg.get(i)); } } }
Published   January 9, 2026
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
🌐
FavTutor
favtutor.com › blogs › foreach-java
For-Each Loop in Java (with Examples)
December 5, 2023 - The forEach loop, introduced in Java 5, provides a simplified syntax for iterating over arrays and collections. The forEach loop is preferred because of its readability and ability to provide a more compact syntax.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › concepts › object.html
What Is an Object? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations.
🌐
ZetCode
zetcode.com › java › foreach
Java forEach - forEach on Java lists, maps, sets
June 17, 2025 - We explore its application with ... various data structures. The forEach method executes a specified action for each element within an Iterable object, continuing until all elements are processed or an exception occurs....
🌐
Baeldung
baeldung.com › home › java › core java › the for-each loop in java
The for-each Loop in Java | Baeldung
January 8, 2024 - In this tutorial, we’ll discuss the for-each loop in Java along with its syntax, working, and code examples.
🌐
Crunchify
crunchify.com › java j2ee tutorials › how to iterate through java list? seven (7) ways to iterate through loop in java
How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java • Crunchify
December 28, 2025 - Hi Lee – try saving each iteration value to array and if required in multidimensional array. Are you looking for complete code? Or conceptually? ... For Loop: 0.015s For Loop Object: 0.229s While Iterator: 0.021s While Loop: 0.01s Stream ForEach: 0.394s
🌐
Oracle
docs.oracle.com › en › java › javase › 26 › docs › api › java.base › java › lang › Object.html
Object (Java SE 26 & JDK 26)
2 weeks ago - It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other.