GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics , method call problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics , method call problem" Watch "Generics , method call problem" New topic
Author

Generics , method call problem

kshitij dogra
Ranch Hand

Joined: Dec 28, 2008
Posts: 39
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.........


SCJP 5.0 - 100%
Arie Prastowo
Greenhorn

Joined: Apr 20, 2008
Posts: 22
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).


SCJP 5.0<br />Use the power of mind
suresh mandalapu
Ranch Hand

Joined: Sep 14, 2008
Posts: 32
call like this
public static <T> void addandDisp(Collection<T extends Object> cs, T t)
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
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?


SCJP 6
M Kothawade
Greenhorn

Joined: Dec 29, 2008
Posts: 9
This is excellent tutorial.
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 598

The uncommented lines..
s has not been defined..


===>SCJP 1.5(72%)<===
==>SCWCD1.5(76%)<===
kshitij dogra
Ranch Hand

Joined: Dec 28, 2008
Posts: 39
thanks I got it
 
GeeCON Prague 2014
 
subject: Generics , method call problem