File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics , method call problem

 
kshitij dogra
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;

class help
{
public static void main(String[] args)
{
System.out.println("Hello World!");
List<Object> ls1 = new LinkedList<Object>();
addandDisp(ls1,new String("help-me"));

}
public static <T> void addandDisp(Collection<T> cs, T t)
{
for (T o : cs)
{
//s.add(o);
}

for (T o : cs)
{
}
}

}



could anybody please tell me, how is the call to the generic method in this case is being made... Specially the second argument which in this case is a String object...

what I thought was , that as T is chosen to be an Object, only an Object instance could be passed through in the second arg (the basic meaning of generics, i.e. type matching)...

Thank you.........
 
Arie Prastowo
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
In method(Collection<T> cs,T t), if you assume T in collection is Object, than, the second argument can be anything from Object to it's subclasses.

Because in runtime, what will happen is the method signature become method(Collection<Object> cs, Object t).
 
suresh mandalapu
Ranch Hand
Posts: 32
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
call like this
public static <T> void addandDisp(Collection<T extends Object> cs, T t)
 
Punit Singh
Ranch Hand
Posts: 952
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But what is the problem, I did not get any problem in addandDisp(ls1,new String("help-me")); call. It is working.

addandDisp(ls1,new String("help-me"));

when calling it will become addandDisp(Object,Object); as String is a subclass of object.

and method will become


so where is the problem?
 
M Kothawade
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is excellent tutorial.
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The uncommented lines..
s has not been defined..
 
kshitij dogra
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks I got it
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic