• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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.
 
I think I'll just lie down here for a second. And ponder this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic