java.lang.ClassCastException: [Ljava.lang.Object; 不能转换为 [Ljava.lang.String;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22731706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:33:30  来源:igfitidea点击:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

javaarraysdictionary

提问by HymanSun

I need convert HashMap to a String array, follow is my java code

我需要将 HashMap 转换为 String 数组,下面是我的 java 代码

import java.util.HashMap;
import java.util.Map;

public class demo {

    public static void main(String[] args) {

        Map<String, String> map1 = new HashMap<String, String>();

        map1.put("1", "1");
        map1.put("2", "2");
        map1.put("3", "3");

        String[] str = (String[]) map1.keySet().toArray();

        for(int i=0; i<str.length;i++) {
            System.out.println(str[i]);
        }
    }
}

when I run the code, I get the following ClassCastException.

当我运行代码时,我得到以下内容ClassCastException

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at demo.main(demo.java:17)

采纳答案by Mureinik

toArray()returns an Object[], regardless of generics. You could use the overloaded variant instead:

toArray()Object[]无论泛型如何,都返回。您可以改用重载的变体:

String[] str = map1.keySet().toArray(new String[map1.size()]);

Alternatively, since a Set's toArraymethod gives no guarantee about the order, and all you're using the array for is printing out the values, you could iterate the keySet()directly:

或者,由于 aSettoArray方法不保证顺序,并且您使用数组的所有内容都是打印出值,您可以keySet()直接迭代:

for (String str: map1.keySet()) {
    System.out.println(str);
}

EDIT: Just to complete the picture, in Java 8, the foreachmethod can be used to make the code more elegant:

编辑:只是为了完成图片,在Java 8中,foreach可以使用该方法使代码更优雅:

map1.keySet().forEach(System.out::println);

回答by Sabuj Hassan

It is returning Object[]Not String[]. Try this:

它正在返回Object[]Not String[]。尝试这个:

Object[] obj = (Object[]) map1.keySet().toArray();
for(int i=0; i<obj.length;i++) {
    String someString = (String)obj[i];
    System.out.println(someString);
}

回答by Mr.Q

toArray()method is defined in List interface so every where there is an instance of List, you also have access to this method.

toArray()方法是在 List 接口中定义的,所以每一个有 List 实例的地方,你也可以访问这个方法。

At first you might think that you can cast an array of Objects which its elements are all of type String to a String array but java specs says otherwise Link, in short it says:

起初,您可能认为可以将其元素都是 String 类型的 Objects 数组强制转换为 String 数组,但 java 规范中另有说明Link,简而言之:

bArr = new B[]; A[] aArr = (A[]) bArr;

bArr = new B[]; A[] aArr = (A[]) bArr;

"works" at runtime if and only if B is a subtype of A (or A itself). Whether B actually only contains As is irrelevant and the compile-time type of bArr is not used either (what matters is the runtime type):

当且仅当 B 是 A(或 A 本身)的子类型时,在运行时“有效”。B 是否实际上只包含 As 无关紧要,也不使用 bArr 的编译时类型(重要的是运行时类型):

In your code by calling : image_urls.toArray()you will get an array of Object and since Object is not SubType of String, you get exception. To do this write, use other overload of toArray()which gets an array of certain type (for type reference) as "Mureinik" mentioned.

在您的代码中,通过调用 :image_urls.toArray()您将获得一个 Object 数组,并且由于 Object 不是 String 的 SubType,您会得到异常。为此,请使用其他重载toArray()获取特定类型的数组(用于类型引用),如提到的“Mureinik”。