I have a created a LinkedList
with an Employee
object stored in it. I need to write a method convertToArray
that would make an array of Employee
s by taking it from the LinkedList
.
Any ideas?
I have a created a LinkedList
with an Employee
object stored in it. I need to write a method convertToArray
that would make an array of Employee
s by taking it from the LinkedList
.
Any ideas?
The easiest way to do this is to utilize LinkedList.toArray method
// create an array and copy the list to it
Employee[] array = list.toArray(new Employee[list.size()]);
However, if you are just learning and would like to do this iteratively. Think about how you would declare and get all of the items into an array.
First, what do you need to do?
1) Declare the array of Employee's
In order to do that, you to know how big to make the array since the size of an array cannot be changed after declaration. There is a method inherited from List called .size()
Employee[] array = new Employee[list.size()]
2) For each slot in the array, copy the corresponding element in the list
To do this, you need to utilize a for loop
for(int i = 0; i < array.length; i++) {
//access element from list, assign it to array[i]
}
public <T> T[] convert (List<T> list) {
if(list.size() == 0 ) {
return null;
}
T[] array = (T[])Array.newInstance(list.get(0).getClass(), list.size());
for (int i=0;i<list.size();i++) {
array[i] = list.get(i);
}
return array;
}
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
arr[i] = e;
i++;
}