• 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

How to Call Generic Method

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Would you please help me to make this work. I modified one of the
K&B exam question as follows:

code:
import java.util.*;
class BackLister {
public static <T> List<? super T> backwards(List<T> input)
{
List<T> output = new LinkedList<T>();
for (T t : input)
output.add(0, t);
return output;
}
}
public class TGeneric96 {
public static void main(String[] args) {
BackLister bl = new BackLister();
List<Integer> ln = new ArrayList();
ln.add (1);
ln.add(2);
ln.add(3);
List<Number> lo = bl.backwards (ln);
System.out.println (lo);
}
}

At Line 19, there is compile error as follows:
TGeneric96.java:19: incompatible types
found : java.util.List<capture of ? super java.lang.Integer>
required: java.util.List<java.lang.Number>
List<Number> lo = bl.backwards (ln);
^

/code
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can assign the List as:

List<? super Integer> lo = BackLister.backwards (ln);

However elements in this List can only be accessed as Objects unless an expicit cast is made, provided that cast doesn't fail at runtime.

Object o = lo.get(0);

or:

Integer i = (Integer) lo.get(0);

The method is declaring that it will return a List who's parmeterized type is Integer or one of its superclasses. That could mean a List<Number> will be returned, but that could also mean a List<Object> will be returned. So the compiler can't assume that the assignment will work.
 
Eleanor Leong
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks very much for your help.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic