Why am i unable to use String but Object

So from this code ( https://code.sololearn.com/cz6UD5xt885w/?ref=app ), starting from the line that has the variable "exName", why is it that when I changed the data-type from String[] to Object[], it will work as expected but not otherwise. Isn't the returned array supposed to have Strings as it items ?

1/26/2020 2:26:38 PM


4 Answers

New Answer


Line 21 should be: .toArray(String[]::new); Otherwise the toArray() without overload, always returns an array of Object. Solution found on https://www.baeldung.com/java-stream-to-array


Arghh. Tibor Santa You beat me to it. xD Btw, if you are interested, class casting rules in Java are documented here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.5.3 The general idea, I believe, is that a String is an Object, but an Object may not be a string. As such, attempting to assign an Object to a String fails the check, unless you tell the compiler explicitly, that you know what you are doing. Observe: String a = ""; Object b = ""; a = b; // fails a = (String)b; // OK b = a; // OK However, explicitly telling the compiler to cast Object to String only works if the Object is actually indeed a String instance and not an Object instance. Compare Object b = new String(""); String a = (String)b; and Object b = new Object(); String a = (String)b; The latter throws a ClassCastException. If you tried to cast Object[] to String[] in your code, I believe this was what would have happened. The only solution was as Tibor pointed out; either that or you loop through the Object array and call .toString() on each of the elements (but this would be redundant since printing Object implicitly calls toString).


Tibor Santa Hatsy Rei Thanks, that's like straightforward..I didn't think of that and it works for primitive types. https://code.sololearn.com/cLXgNtigyuMu/?ref=app But a new question arise, keeping the code as it is in the description then If I added an annotation of suppresswarning to it, it will also work as expected..is annotation doing something to the code, I thought they're useless


I am not sure how you managed to suppress this as your original code fails to compile for me. SuppressWarnings is only supposed to silence the warnings, not the errors, or am I wrong? Anyway the warning is also a sign that your code is not perfect or does not fully comply with the intended use of the language, so it is always best to fix the issue when possible, instead of suppressing it... My opinion.