Reputation: 15
I am learning Java and I am wondering one thing:
Do I need for
-loops for arraylist, before one can consider it as arraylist? Because every example I find, shows me some sort of a loop.
So will you consider this as arraylist?
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
And then use the elements from the list in methods etc.
Or is this better(even if the first example is good enough for you):
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
for (int i = 0; i < stringList.size(); i++)
String item = stringList.get(i);
System.out.println("Item " + i + " : " + item);
}
Upvotes: 0
Views: 94
Reputation: 30746
You absolutely do not need to use loop control structures when dealing with collections. Often you can write cleaner collection-manipulating code using a library like Guava.
Upvotes: 0
Reputation: 62062
No, you do not have to use loops when using collections. There's nothing wrong with not using loops. Although, in almost every situation where you're going to use some sort of collection, you're going to want to be using some sort of a loop.
One exception I might see where you need to use a collection and definitely won't loop with it is if you're using a method that takes a collection as an argument and you can't override, but you want to perform whatever operation on a single object.
In this case, you could load an ArrayList
with a single string so that that single string could be sent to the method via the collection.
Also, in both Android and iOS programming, you will frequently see some sort of collection used in order to save user settings, and these aren't necessarily used in loops.
Upvotes: 1