public class example {
static ArrayList<String[]> test = new ArrayList<String[]>();
private String[] a = {"this", "is,", "a test"};
private String[] b = {"Look", "a three-headed", "monkey"};
public void fillTest() {
test.add(a);
test.add(b);
// so far so good, I checked this method
// with a System.out.print and it works
}
// later in the code I have a method that try
// to take the arrayList test and copy it into
// a String[] named temp. In my vision temp
// should than be accessed randomly by the
// method itself and the content printed out
// from temp should be removed from test -
// that's why I'm using an ArrayList
public void stuff() {
// some stuff
// runtime error happens here:
String[] temp = test.toArray(new String[test.size()]);
// other stuff that never made it to runtime
}
}
Проблема в том, что пока компилятор ничего против этого не имеет, в Runtime получаю вот такую ошибку:
Исключение в потоке "main" java.lang.ArrayStoreException: arraycopy: несоответствие типа элемента: невозможно привести один из элементов java.lang.Object[] к типу целевого массива, java.lang.String
Я не могу понять причину - мне кажется, я прошу заполнить массив строк строками, так почему ошибка?
Вы пытаетесь преобразовать List
, элементами которого являются массивы String
, в массив, элементами которого являются String
s. Это не работает, так как массив String
не является String
.
Вместо этого вы можете преобразовать List
массивов в 2D-массив String
s:
String[][] temp = test.toArray(new String[test.size()][]);
Если вы хотите поместить все элементы массивов строк List
в один массив String
, вам нужно выполнить некоторую обработку. С Stream
s это можно сделать с помощью:
String[] temp = test.stream().flatMap(Arrays::stream).toArray(String[]::new);
Вы можете использовать метод Stream.flatMap, чтобы сгладить этот список массивов строк и получить поток по одному массиву строк. И тогда вы можете получить массив, содержащий элементы этого потока:
List<String[]> test = Arrays.asList(
new String[]{"this", "is,", "a test"},
new String[]{"Look", "a three-headed", "monkey"});
String[] temp = test
// return Stream<String[]>
.stream()
// return Stream<String>
.flatMap(arr -> Arrays.stream(arr))
// return an array of a specified size
.toArray(size -> new String[size]);
System.out.println(Arrays.toString(temp));
// [this, is,, a test, Look, a three-headed, monkey]
See also: Is there any way to convert a 2D List to 1D List using only 'map' not using 'flatMap'?