質問

Before asking for help , i am really sorry if this is a duplicate question or bad question because i did not know what to search.

There is a thing that is bothering me while playing with arrays in java. Here is code:

String []stt = new String[5];
stt[0].length();  //of course NullPointerException because uninitialized.
System.out.println(stt.getClass()); //it should return class of array instead of String.

According to above code, there is no String Object created till now and stt should be of Array type not String type ,in fact elements inside stt should be of String type.

I wanted to know what is the class of array objects and it is supposed to return class of array objects.

役に立ちましたか?

解決

The class of what the reference is pointing to is a String array. if you want to test to see if that reference is part of an array, then there is a special method for that, isArray.

System.out.println(stt.getClass().isArray());

As some other have noted, with a closer look you can see the difference in the output just using

class [Ljava.lang.String; // Array of String
class java.lang.String    // String

他のヒント

Running this code:

String []stt = new String[5];
System.out.println(stt.getClass());

prints

class [Ljava.lang.String;
      ^^

The [L at the beginning means Array, the rest is obviously String. Together: String array.

The statement System.out.println( stt.getClass() ); actually returns an array. If you have observed keenly, the output is class [Ljava.lang.String; but not class java.lang.String. [ denotes representation for an Array.

To check if the output is an array or not you can try the stament stt.getClass().isArray() which returns a boolean.

Arrays in Java are not of a seperate type. So the class of an array of Strings is still String. The class Array is merely a collection of static methods to work with arrays and you cannot make instances of it. As pointed out in other answers you can use the isArray method from Class to determine whether the object is an array.

Alternatively, you can use instanceof:

boolean isStringArray(Object o){
return o instanceof String[];
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top