• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Type compatibility question - Question about Why

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Sergej I will take a look at the link!

Kirk
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic