-2

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 Employees by taking it from the LinkedList.

Any ideas?

admdrew
  • 3,600
  • 4
  • 22
  • 39

3 Answers3

4

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]
}
Chris Manning
  • 429
  • 4
  • 14
  • 1
    It's a minor point, but the array passed to `toArray` can be any length, including 0. `toArray` will return a newly-allocated array of the same type. – Jeff Bowman Dec 05 '14 at 22:20
  • 2
    @JeffBowman If you pass in an array of the right size, the method won't have to create another one of the right size to return to you. – khelwood Dec 05 '14 at 22:22
  • Fair enough. I'd forgotten that the array instance is [reused if possible](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#toArray(T%5B%5D)). – Jeff Bowman Dec 05 '14 at 22:33
2
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;
}
outdev
  • 4,578
  • 2
  • 17
  • 33
1
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
  arr[i] = e;
  i++;
}
MasterCassim
  • 8,500
  • 3
  • 22
  • 30