Skip to main content

iterate through the elements of a array in a loop Java without explicitly specifying?

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
PoolMan
Offline
Joined: 2012-05-20

It is possible to iterate through the elements of a array in a loop Java without explicitly specifying the number of elements in the array?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
grelf
Offline
Joined: 2007-11-14

Yes, simply by using a for-each loop:

Object [] myArray = ....; // Whatever

for (Object obj : myArray)
{
...
}

However, you would have had to set the array size before using it. If you really want a collection with a variable size look at java.util.ArrayList