. lang。ClassCastException:[Ljava.lang.Object;不能被转换为[Ljava.lang.String];

时间:2021-06-27 15:51:58

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

我需要将HashMap转换为String数组,follow是我的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)

I am confused with this, who can help me.

我很困惑,谁能帮我。

3 个解决方案

#1


22  

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

toArray()返回一个对象[],而不考虑泛型。您可以使用重载的变体:

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

Alternatively, since a Set's toArray method 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:

另外,由于Set的toArray方法不能保证顺序,而您使用该数组的目的是打印出值,因此可以直接迭代keySet():

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

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

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

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

#2


5  

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

它返回的是对象[]而不是字符串[]。试试这个:

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

#3


1  

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

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

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:

一开始,你可能会认为你可以将一个对象数组的元素都是字符串类型的元素投射到一个字符串数组中,但是java spec说,否则链接,简而言之,它说:

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

巴尔=新的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(),您将获得一个对象数组,由于对象不是字符串的子类型,您将获得异常。要执行此写入操作,请使用toArray()的其他重载,该重载获取特定类型(用于类型引用)的数组,如“Mureinik”所述。

#1


22  

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

toArray()返回一个对象[],而不考虑泛型。您可以使用重载的变体:

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

Alternatively, since a Set's toArray method 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:

另外,由于Set的toArray方法不能保证顺序,而您使用该数组的目的是打印出值,因此可以直接迭代keySet():

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

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

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

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

#2


5  

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

它返回的是对象[]而不是字符串[]。试试这个:

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

#3


1  

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

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

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:

一开始,你可能会认为你可以将一个对象数组的元素都是字符串类型的元素投射到一个字符串数组中,但是java spec说,否则链接,简而言之,它说:

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

巴尔=新的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(),您将获得一个对象数组,由于对象不是字符串的子类型,您将获得异常。要执行此写入操作,请使用toArray()的其他重载,该重载获取特定类型(用于类型引用)的数组,如“Mureinik”所述。