优秀的编程知识分享平台

网站首页 > 技术文章 正文

编码规范-Java:使用Collection.toArray抛出ClassCastException

nanyue 2024-08-26 18:03:22 技术文章 6 ℃

编号

Basic22

标题

使用Collection.toArray()方法会抛出ClassCastException

语言

Java

级别

1

类别

基础

规范说明

如果您需要从Collection获取某个类的数组,您应该将期望的类数组作为toArray方法的参数传递。否则,您将获得ClassCastException。

import java.util.ArrayList;
import java.util.Collection;

public class Test {

    public static void main(String[] args) {
        Collection c=new ArrayList();
        Integer obj=new Integer(1);
        c.add(obj);

        // this would trigger the rule (and throw a ClassCastException
if executed)
        Integer[] a=(Integer [])c.toArray();

        // this wouldn't trigger the rule
        Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);
    }
}

Tags:

最近发表
标签列表