For each syntax

Can someone tell me what is going on here? It seems to me that myObj is passed to String [], so it can be repeated in a for loop. But it was created as a new String [] - why should it be cast?

public static void main(String args[]) { Object myObj = new String[]{"one", "two", "three"}; for (String s : (String[])myObj) { System.out.print(s + "."); } } 

Thanks!

+4
source share
5 answers

It does not matter that it was created as String[] ; you only have an Object link. It is not related to everyone; The following will not compile:

 Object myObj = new String[]{"one", "two", "three"}; System.out.println(myObj.length); // There is no Object.length 
+5
source

When you declared myObj as Object , you told him to forget that this is something else.

+2
source

Why not declare the array as the actual type? eg:

 Syting[] myObj = new String[]{"one", "two", "three"}; 

Therefore, casting is not required

0
source

There is a difference between the apparent type and the actual type. The myObj [] Object statement tells Java that you are declaring an array of objects. At compile time, this is the only type that interests Java. Later, when you try to access the elements of an array, Java accepts an Object and nothing else. The string is called the actual type and is only "known" at runtime. hence the reason for casting.

0
source

The type of object you are trying to iterate is checked at compile time. And at compile time, the only information available is the declared type of the variable. The compiler cannot [reliable, always] find out that you are actually putting String [] there (google "stopping problem" to find out why).
Runtime-type information is used for polymorphism, such as casting, perhaps other things that I can't think of right now.

0
source

Source: https://habr.com/ru/post/1381028/


All Articles