-1

I implemented a linkedList in Java and now I am working on a new method toArray in order to sort the link list after. I am getting an error when I am trying to print each elements of the ArrayList Cannot resolve method 'toString(java.util.List)'

public class Node {
  int value;
  Node next;
}

public class LinkedList {
  Node head;

  public void toArray(LinkedList list){   
    List<Integer> temp = new ArrayList<>();
    Node iterator = head;

    while(iterator != null){
      temp.add(iterator.value);
      iterator = iterator.next;
    }

    temp.forEach(arr->System.out.println(Arrays.toString(temp)));
  }
  • 3
    Possible duplicate of [Convert ArrayList to String\[\] array](https://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string-array) – pvpkiran Sep 30 '19 at 13:10

2 Answers2

2

This expression is wrong:

System.out.println(Arrays.toString(temp))

Because temp is an ArrayList, not an Array. Try this:

System.out.println(temp)

By the way, you still have some errors in your code, this should fix them:

public void toArray() {

    List<Integer> temp = new ArrayList<>();

    Node iterator = head;
    while (iterator != null) {
        temp.add(iterator.value);
        iterator = iterator.next;
    }

    temp.forEach(System.out::println);

}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

The method Arrays.toString() needs an Array in argument.
You need transform you List an one Array calling the method: toArray().
Like this:

temp.forEach(arr->System.out.println(Arrays.toString(temp.toArray())));
artsmandev
  • 156
  • 6