I think I'm missing something basic here. Any explanation or pointers to previously asked questions will be very helpful.
import java.util.Arrays;
import java.util.List;
public class St {
public static void bla(Object[] gaga) {
gaga[0] = new Date(); // throws ArrayStoreException
System.out.println(gaga[0]);
}
public static void bla(List<Object> gaga) {
System.out.println(gaga.get(0));
}
public static void main(String[] args) {
String[] nana = { "bla" };
bla(nana); // Works fine
List<String> bla1 = Arrays.asList(args);
bla(bla1); // Wont compile
System.out.println(new String[0] instanceof Object[]); // prints true
System.out.println(nana.getClass().getSuperclass().getSimpleName()); // prints Object
}
}
So, it seems like a List<String>
is not a subclass of a List<Object>
but a String[]
is a subclass of Object[]
.
Is this a valid assumption? If so, why? If not, why?
Thanks
As String class is the subclass of Object class how the return type of toString() method in the Object class is String.
String is a subtype of Object , because the String class is a subclass of the Object class.
The built-in class String has the class Object as its superclass. Since the class String has no subclasses, the only values of type String are instances of the class String. In contrast, the built-in class Number is a child of class Object and has several subclasses including Integer and Float.
Java String array is basically an array of objects. There are two ways to declare string array - declaration without size and declare with size. There are two ways to initialize string array - at the time of declaration, populating values after declaration.
Java arrays are covariant, i.e. they allow Object[] foo = new String[2];
. But this doesn't mean they are subclasses. String[]
is a subclass of Object
(although instanceof
returns true, String[].class.getSuperclass()
returns Object
)
Yes, your assumption is valid. As said by @Bozho arrays are covariant, whereas generic collections (such as generic List) are not covariant.
Covariance in arrays is risky:
String[] strings = new String[] { "a", "b" }
Object[] objects = strings;
objects[0] = new Date(); // <-- Runtime error here
String s = strings[0];
s.substring(5, 3); // ????!! s is not a String
The third line fires a runtime exception. If it weren't firing this exception then you could get a String
variable, s
, that references a value that is not a String
(nor a subtype thereof): a Date
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With