• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Arrays.asList() and guessing type

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
from Thinking in Java:


Why does it (Arrays.asList) make a guess about the type? Upcasting doesn't work? How does it work?
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

The declaration of asList is : public static <T> List<T> asList(T... a)
So when you write : List<Snow> snow2 = Arrays.asList(a); the compiler expects that a is an array of Snow. OK
When you give a to asList, the compiler has to find the type of a.
With asList(new Light(), new Heavy()); the compiler finds that the "common denominator" for the type is Powder and not Snow ! So it complains.
With asList(new Powder(), new Crusty()); the common denominator is ... Snow, so the compiler is happy.

For addAll the declaration is : boolean addAll(Collection<? extends E> c)
So, in a List of Snow, you can add any object whose the type extends Snow.
Tht's why


List<Snow> snow3 = new ArrayList<Snow>();
Collections.addAll(snow3, new Light(), new Heavy());


works fine.

I hope it's quite clear and above all that I didn't any mistake.
 
Piotr Milewski
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So... when we write:

"Arrays.asList" doesn't see "List<Snow> snow1", so it has to presume the type only by the part: "Arrays.asList(new Crusty(), new Slush(), new Powder())"

OK, thanks
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic