Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Type compatibility question - Question about Why

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below doesn't compile due to a type compatibility error on line 8. I understand that. What I would like to know is the why??

Why is it that line 7 compiles just fine. In line 7 Arrays.asList() returns a List<Integer> and assigns it to a List<Number>. In line 8 new ArrayList<Integer> is being attempted to assigned to ArrayList<Number>. Why is that not allowed where as the assignment of List<Integer> to List<Number> is allowed.

The javadoc for Arrays.asList says: public static <T> List<T> asList(T....a).


 
Ranch Hand
Posts: 472
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
This page has excellent pdf file with explanation how generic work. I think if you read you will find answer.
Simple answer is: this how generic works
also

Test.java:7: error: incompatible types: List<Integer> cannot be converted to List<Number>
List<Number> list = Arrays.asList(s);
^
Test.java:8: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number>
ArrayList<Number> lis2 = new ArrayList<Integer>();
^


for java 7.
in java 8 result differ, because List<Number> take in account to get type of T.
 
Kirk Rohani
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sergej I will take a look at the link!

Kirk
 
I claim this furniture in the name of The Ottoman Empire! You can keep this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic