简体   繁体   English

String[] 方法返回一个非空的 java

[英]String[] method returns a not-null java

I recently ported my eclipse project to IJ recently and my array randomizer returns following error我最近将我的 eclipse 项目移植到 IJ,我的数组随机化器返回以下错误

java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')
    at Constants.func.ranArr(func.java:42)

and

(String[]) i.toArray();in func.ranArr(String[])(filter not-null)

this is the code of the method这是方法的代码

    public static String[] ranArr(String[] arr) {
        List<String> i = Arrays.asList(arr);
        Collections.shuffle(i);
        String[] r = (String[]) i.toArray();
        return r;
    }

How do I fix it, it worked in Eclipse我该如何修复它,它在 Eclipse 中有效

You can replace (String[]) i.toArray() by i.toArray(new String[0]) .您可以将(String[]) i.toArray()替换为i.toArray(new String[0])

Because an ArrayList can store items of any type, internally it uses a Object[] to store the array's contents.因为 ArrayList 可以存储任何类型的项目,所以它在内部使用Object[]来存储数组的内容。

When you call toArray() , it simply returns a copy of that internal array, which is again an Object[] .当您调用toArray()时,它只是返回该内部数组的副本,它又是一个Object[]

In fact, because of type erasure (the fact that an instance of a generic type doesn't know at runtime what type its type parameters are) the ArrayList can't do anything else.事实上,由于类型擦除(泛型实例在运行时不知道其类型参数是什么类型的事实), ArrayList不能做任何其他事情。

As you know that you are storing Strings, you can use toArray(new String[0]) , as @Timur suggested.如您所知,您正在存储字符串,您可以按照@Timur 的建议使用toArray(new String[0])

That function will look at the type of the array you pass and create a new array with that type. function 将查看您传递的数组类型并创建一个具有该类型的新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM