【问题标题】:How to print a specific String stored into an array of String into an ArrayList of Strings Arrays?如何将存储在字符串数组中的特定字符串打印到字符串数组的 ArrayList 中?
【发布时间】:2021-03-28 01:52:17
【问题描述】:

所以,根据问题,我在 Java 中有这段代码:
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
    }
}

问题是,虽然编译器对此没有任何反对意见,但在运行时我得到了这个错误:

线程“main”中的异常 java.lang.ArrayStoreException:arraycopy:元素类型不匹配:无法将 java.lang.Object[] 的元素之一转换为目标数组的类型 java.lang.String

我无法理解背后的原因 - 在我看来,我要求它用字符串填充一个字符串数组,那么为什么会出现错误?

【问题讨论】:

    标签: java arrays arraylist toarray arraystoreexception


    【解决方案1】:

    您正在尝试将元素为String 的数组的List 转换为元素为Strings 的数组。这不起作用,因为String 的数组不是String

    相反,您可以将List 数组转换为Strings 的二维数组:

    String[][] temp = test.toArray(new String[test.size()][]);
    

    如果要将List的String数组的所有元素都放在String的单个数组中,就得做一些处理。使用Streams 可以做到:

    String[] temp = test.stream().flatMap(Arrays::stream).toArray(String[]::new);
    

    【讨论】:

      【解决方案2】:

      您可以使用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]
      

      另见:Is there any way to convert a 2D List to 1D List using only 'map' not using 'flatMap'?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2019-11-23
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        • 2023-03-07
        相关资源
        最近更新 更多