-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?

2
  • What effort have you made so far? Commented Dec 5, 2014 at 22:17
  • Well, you can try getting the size of the linked list.. what would you do next? can you traverse the linked list? can you have an array of the same size? try something. Commented Dec 5, 2014 at 22:18

3 Answers 3

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]
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
Fair enough. I'd forgotten that the array instance is reused if possible.
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;
}

2 Comments

i need to put it into a method where i can convert any linked list into an Array. public void convertToArray() is that how i would do it?
Is this method working for you
1
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
  arr[i] = e;
  i++;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.