Results 1 to 5 of 5
- 04-01-2014, 09:15 PM #1
Senior Member
- Join Date
- Mar 2014
- Posts
- 286
- Rep Power
- 7
Generic types in java - basic concept
I am trying to understand the concept of Generics in java. In the introduction to Generic Types, this example is given:
Java Code:public class Box { private Object object; public void set(Object object) { this.object = object; } public Object get() { return object; } }
But then it has been changed to a generic class:
Java Code:/** * Generic version of the Box class. * @param <T> the type of the value being boxed */ public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
We can use any type in place of an Object, because Object is a superclass of all classes. But T (or any other class) is not a superclass of all classes. So how do we justify any class being used in place of a random T or any other class?
Thank you in advance.
- 04-01-2014, 09:47 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
Re: Generic types in java - basic concept
... by filling in any 'real' type for 'T' (as in Box<String>, Box<Double> etc.)
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
- 04-01-2014, 09:59 PM #3
Senior Member
- Join Date
- Mar 2014
- Posts
- 286
- Rep Power
- 7
Re: Generic types in java - basic concept
"One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error."
Reference: Generic Types (The Java™ Tutorials > Learning the Java Language > Generics (Updated))
- 04-01-2014, 10:17 PM #4
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: Generic types in java - basic concept
That is the primary reason for generics. So your potential run time errors will be caught at compile time. In most cases it also frees you from having to use instanceof and then casting objects to the proper type. So the code becomes more readable.
Regards,
JimThe JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 04-01-2014, 10:29 PM #5
Senior Member
- Join Date
- Mar 2014
- Posts
- 286
- Rep Power
- 7
Similar Threads
-
Can you help me understand this basic GUI concept?
By EscSequenceAlpha in forum New To JavaReplies: 1Last Post: 04-08-2012, 09:33 PM -
Arithmetic with Generic Types
By azalea in forum New To JavaReplies: 3Last Post: 10-24-2011, 09:55 PM -
generic and different enum types
By vojtab in forum New To JavaReplies: 0Last Post: 11-08-2010, 06:11 PM -
Help with comparing generic types
By repairmanjack in forum New To JavaReplies: 4Last Post: 09-22-2009, 07:41 AM -
generic types
By jon80 in forum New To JavaReplies: 6Last Post: 06-12-2009, 11:29 PM
Bookmarks