Reputation: 13
I was wondering how exactly to create an ArrayList
of an array of objects. For example
Object[] objectArray = new Object() // Varying amount of object[]
I would like to add Object[]
to an ArrayList
as they come in. I have seen that an ArrayList
of arrays can be created by the following:
ArrayList<String[]> action = new ArrayList<String[]>();
So I was thinking it would be as simple as:
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
But apparently not.
Upvotes: 0
Views: 132
Reputation: 23
It's a easy stuff.
// Class Student with a attribute name
public class Student{
String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public static void main(String[] args) {
// Creating an ArrayList for Students
ArrayList<Student> students = new ArrayList<Student>();
// Creating an Students Objects
Student a1 = new Student("Name1");
Student a2 = new Student("Name2");
Student a3 = new Student("Name3");
// Populating ArrayList<Student>
students.add(a1);
students.add(a2);
students.add(a3);
// For Each to sweeping all objects inside of this ArrayList
for(Student student : students){
System.out.println(student.getName());
}
}
Enjoy!
Upvotes: 0
Reputation: 1146
So, you have two questions:
Object[] objectArray = new Object()
ArrayList<objectArray[]> action = new ArrayList<objectArray[]>();
Change it to:
int MAX_ARRAY = 3;
Object[] objectArray = new Object[MAX_ARRAY];
ArrayList<Object[]> action = new ArrayList<Object[]>();
Now you can add your objectArray to "action":
action.add(objectArray);
Upvotes: 0
Reputation: 72844
The type parameter in the generic List
class should be the class name and not the name of the variable that references the array:
ArrayList<Object[]> action = new ArrayList<Object[]>();
Two notes:
Try to avoid declaring types to the implementations. Declare action
as a List
(the interface):
List<Object[]> action = new ArrayList<Object[]>();
It would make life a bit easier if you make the parameter another List
instead of an array of Object
s:
List<List<?>> action = new ArrayList<List<?>>();
Upvotes: 1
Reputation: 146
ArrayList<LoadClass[]> sd = new ArrayList<LoadClass[]>();
This works :)
Upvotes: 0
Reputation: 393781
You create an ArrayList of arrays this way :
ArrayList<Object[]> action = new ArrayList<Object[]>();
Each time you add an Object[] to that list, it must have a fixed length.
If you want variable length arrays inside the ArrayList, I suggest you use ArrayList<ArrayList<Object>>
.
Your syntax with objectArray
is simply not valid Java syntax.
Upvotes: 2