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 doubt

 
megha joshi
Ranch Hand
Posts: 206
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
megha joshi
Ranch Hand
Posts: 206
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You do realise that the T in this:



is not the same T as you started with in the class definition?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic