Java中数组是不是对象

数组时指具有相同类型的数据的集合,它们一般具有固定的长度,并且在内存中占据连续的空间。在C/C++语言中,数组名只是一个指针,这个指针指向了数组的首元素,既没有属性也没有方法可以调用,而在Java语言中,数组不仅有其自己的属性(例如length属性),也有一些方法可以被调用(例如clone方法)。由于对象的特点是封装了一些数据,同时提供了一些属性和方法,从这个角度来讲,数组是对象。每个数组类型都有其对应的类型,可以通过instanceof来判断数据的类型。

public class Test {
    public static void main(String[] args) {
        int[] a = { 1, 2 };
        int[][] b = new int[2][4];
        String[] s = { "a", "b" };
        if (a instanceof int[]) {
            System.out.println("the type for a is int[]");
        }
        if (b instanceof int[][]) {
            System.out.println("the type for a is int[][]");
        }
        if (s instanceof String[]) {
            System.out.println("the type for a is String[]");
        }
    }
}
/**
 * the type for a is int[]
 * the type for a is int[][]
 * the type for a is String[]
 */

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/83447656