In Java, is a char[] an object?

2020-07-18 02:09发布

I'm new to Java but if I understand correctly, a char is a primitive.

Doing char temp and temp.hashCode() won't compile but doing a char[] temp2 = new char[2] and temp2.hashCode() will compile and execute.

Does this mean somehow a char[] is an object???

6条回答
\"骚年 ilove
2楼-- · 2020-07-18 02:42

Yes, all arrays are Objects in Java.

查看更多
别忘想泡老子
3楼-- · 2020-07-18 02:42

Yes arrays are objects in java.

查看更多
姐就是有狂的资本
4楼-- · 2020-07-18 02:48

a char is a primitive, but an array of type char is an object

one way to tell is by dynamically instantiating it:

final Object charArray = Array.newInstance(Character.TYPE, 5);
System.out.println(charArray.getClass().getComponentType());

Output:

char

(Character.TYPE is a reference to the primitive class char. Another way to access that class is through char.class)

查看更多
贼婆χ
5楼-- · 2020-07-18 02:49

Yes. All arrays are objects, even arrays of primitive types.

查看更多
Summer. ? 凉城
6楼-- · 2020-07-18 02:54

Yes, every Array of every type is an object.

查看更多
何必那么认真
7楼-- · 2020-07-18 02:55

An array isn't just several primitive types, it also has a "length" field. Primitive types don't have fields. Another thing that sets arrays appart from primitive types is they are references and thus have to be garbage collected.

查看更多
登录 后发表回答