• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics - Doubt in code  RSS feed

 
Padma priya Gururajan
Ranch Hand
Posts: 437
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a doubt in Generics in the line marked 1
public class Box<T> {

private T t; //line 1

public void add(T t) {
this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}

Can you explain what line 1 mean?
I understand that T is the type parameter.

Thanks.
Padma priya N.G.


 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Padma priya Gururajan wrote:Can you explain what line 1 mean?

It's just a field declaration. And it might have been better if you'd given it a better name, eg:
  private T boxedValue;

One way to imagine it is that whenever you create an object, the compiler goes through the class definition and replaces all instances of 'T' with the type you supply to new; so in the case of your integerBox object, it will be:
  private Integer boxedValue;
because you supplied 'Integer' as the type; and in the case of stringBox, it will be:
  private String boxedValue;

Does that make any more sense?

Winston
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Padma priya Gururajan wrote:Hi,

I have a doubt in Generics in the line marked 1
class Box<T> {

private T t; //line 1

Tip: UseCodeTags (←click on that link) and the Preview feature before you submit your post. That way you get line numbers in your code listing that you can reference without having to add comments like you did.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!