aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics doubt 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 doubt" Watch "Generics doubt" New topic
Author

Generics doubt

megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
Hi,

I am trying to add to a list of bounded parameter type with the following code:
import java.lang.Runnable;
import java.util.*;

class Test<T extends Number> {

public <T extends Number> List<T> makeArrayList(T t)
{
List<T> list = new ArrayList<T>();
list.add(t); //line 2
return list;
}
public void makeArrayListII(){
List<T> list = new ArrayList<T>();
list.add(1.0); //error //line 1


}
public static void main(String args[]){
System.out.println(new Test().makeArrayList(1.0));

}
}

Line 1 gives error while Line 2 doesnt, but in both places I am trying to do the same thing.I dont get what is the difference which is causing the error in one case and no error in another case. Please help.

Thanks,
Megha
Marcos R Oliveira
Ranch Hand

Joined: Apr 20, 2002
Posts: 51
Hi,Megha,

I believe the error happens because ArrayList<E> does not have a method with the signature



When you pass 1.0 as a parameter to the makeArrayList method, it is autoboxed to the T type (or Double, that is a wrapper for 1.0).


SCJP 1.4 - SCJP 1.6 - SCWCD in progress
megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
Ah....got it

So I should have some concrete type here

List<T> list = new ArrayList<T>();
list.add(t); //line 2

Thanks for the help,
Megha
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi,


public void makeArrayListII(){
List<T> list = new ArrayList<T>();
list.add(1.0); //error //line 1
}


Actually you have parameterized the List with type <T>, so you can't add
anything except T in the list. The type is unknown, how do you know it is
double or Integer or Dog or so. But for sure it is type T, so you can add it.

Let me remind you, the scenario where you promised to return List<T> and
were you were not able to return anything except List<T>, not List<String>,
not List<StringBuffer> or so.
The type is unknown, you can't assume it to be double or anytype else.


Thanks,


cmbhatt
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
You do realise that the T in this:



is not the same T as you started with in the class definition?


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics doubt
 
Similar Threads
Generics
Generics wilcard
Generics doubt
about the generic method
"T extends Animal" VS "? extends Animal"