1

I'm wondering, why is there a problem to change Arraylist of File to an array.

public static void main(String[] args) {
    List<File> pl = new ArrayList<File>();
    pl.add(new File ("C:\\folder"));
    String[] k;
    k = pl.toArray(new String[pl.size()]);
    System.out.println(k);
}

In a simple example above I will get:

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(Unknown Source)
    at Main.main(Main.java:25)

and second question: Do I have to pass size of Arraylist? Because both version works fine with arraylist of strings:

k = pl.toArray(new String[pl.size()]);
k = pl.toArray(new String[] {});
1
  • What are you trying to do here? Are you trying to convert a list of files into a list of string contents? Commented Dec 15, 2018 at 14:03

2 Answers 2

3

You have a list of File objects, you can't just put them in an array of String, you'll need to explicitly convert them somehow (e.g. by calling File#getName()). The most convenient way of doing this is probably with a Stream:

k = p1.stream().map(File::getName).toArray(String[]::new);
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to convert Path to String when you want to map a List<Path> into an array.

Here what you could write (I add some comment about changes) :

public static void main(String[] args) {
    List<File> pl = new ArrayList<>(); // Diamond operator
    pl.add(new File ("C:\\folder"));
    File[] k = pl.toArray(new File[pl.size()]);
    k = pl.stream().toArray(File[]::new);  // equivalent to the previous line
    System.out.println(Arrays.toString(k)); // Array.toString is not overriden. So this is needed
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.