Friday 1 December 2017

java - Why List is not acceptable as List?





Consider below method
doSomething(List) which accepts
List as
parameter.



private void
doSomething(List list) {
// do
something
}


Now
consider below code snippet which tries to call doSomething()
where I try to pass List to
doSomething()



List
objectList;
List
stringList;

doSomething(stringList); // compilation error
incompatible types
doSomething(objectList); // works fine



Even below code
throws compilation error



objectList = stringList; //
compilation error incompatible
types


My question is
why List can not be passed to a method which
accepts List?



Answer




This generic question in Java may look
confusing to any one who is not very familiar with Generics as in first glance it looks
like String is object so List can be used where
List is required but this is not true. It will
result in compilation error.



It does make sense
if you go one step further because List
can store anything including
String, Integer etc but
List can only store
Strings.



Also have a
look at: href="https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt">Why
not inherit from List?



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...