数组是原始类型还是对象(或其他完全类型)? [英] Is an array a primitive type or an object (or something else entirely)?

查看:24
本文介绍了数组是原始类型还是对象(或其他完全类型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题基本上是不言自明的.我找不到数组的 API(除了这个 Arrays,但这只是定义了一堆处理实际数组的静态辅助函数).如果没有它的类,这似乎表明数组不能是 Object.

The question is basically self-explanatory. I haven't been able to find an API for arrays (other than this Arrays, but this just defines a bunch of static helper functions for dealing with actual arrays). If there is no class for it, this seems to suggest that an array can't be an Object.

然而,事实上数组具有像 length 这样的公共字段和它可以调用的方法,比如 .equals().clone() 似乎(非常强烈地)暗示了完全相反的情况.

However, the fact that an array has public fields like length and methods that it can invoke like .equals() and .clone() seem to suggest (very strongly) the complete opposite.

对于原始数组的奇怪表现和行为的解释是什么?

What is the explanation for the odd presentation and behavior of primitive arrays?

作为说明,我刚才尝试在数组的 .clone() 方法上使用开放实现"Eclipse 功能,希望我能够看看在哪里以及如何这个方法被定义了(因为它说 int[] 从 Object 覆盖了它),但它实际上导致我的整个 Eclipse 冻结并崩溃......

As a note, I tried to use the "Open Implementation" Eclipse feature on the .clone() method of an array just now, hoping that I would be able to look at where and how this method was defined (since it said int[] overrode it from Object), but it actually caused my entire Eclipse to freeze up and crash...

推荐答案

每个数组类型都有一个类,所以int[]有一个类,Foo有一个类[].这些类是由 JVM 创建的.您可以通过int[].classFoo[].class 访问它们.这些类的直接超类是Object.class

There is a class for every array type, so there's a class for int[], there's a class for Foo[]. These classes are created by JVM. You can access them by int[].class, Foo[].class. The direct super class of these classes are Object.class

public static void main(String[] args)
{
    test(int[].class);
    test(String[].class);
}

static void test(Class clazz)
{
    System.out.println(clazz.getName());
    System.out.println(clazz.getSuperclass());
    for(Class face : clazz.getInterfaces())
        System.out.println(face);
}

还有一个编译时子类型规则,如果AB的子类型,A[]B的子类型[].

There's also a compile-time subtyping rule, if A is subtype of B, A[] is subtype of B[].

这篇关于数组是原始类型还是对象(或其他完全类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆