Reputation: 193
In my hw assignment my professor says to create a data field of type ArrayList. He wants them to be instances of a class. I'm not exactly sure what that means, but my guess is
ArrayList<CLassName> list = ArrayList<ClassName>();
Can anyone confirm this for me?
Upvotes: 1
Views: 60
Reputation: 11234
You can use something like this:
List<String> list = new ArrayList<String>();
Since Java SE 1.7, it can a little simpler:
List<String> list = new ArrayList<>();
Upvotes: 3
Reputation: 16987
Yes, that's right. I do, however, recommend this instead:
List<ClassName> list = new ArrayList<ClassName>();
That way you can change the type of list in just one place instead of two.
Upvotes: 0
Reputation: 13596
Yes.
NOTE: The rest is background knowledge about ArrayLists.
Let's say you want an ArrayList of Strings. Keep in mind Strings are Objects.
// Creates ArrayList
ArrayList<String> list = ArrayList<String>();
// Adds elements to ArrayList
list.add("Hello");
list.add("world!");
// Iterate through ArrayList
for (String str : list) {
// Print the String in the list.
System.out.print(str + " ");
}
// Print newline character.
System.out.print("\n");
The for (String str : list)
is a for each loop which allows you to iterate through each element in the list.
Upvotes: 0