• Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding parameterised classes  RSS feed

 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am having trouble understanding what this line means exactly. Could someone kindly give me an example?

"By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read."

https://docs.oracle.com/javase/tutorial/java/generics/why.html

Thanks,
Prasanna
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means you can insist that your List only take Strings as its elements.
List<String> pronounced, “List of Strings”.
You know you can only put Strings into it.
You know you can only take Strings out of it.
You know it can only contain Strings.

Before generics (which should have been implemented in Java1.0), you had to cast thingsWhat if this line were inserted between lines 3 and 5?
list.add(new Integer(123));
You wouldn't know anything was wrong until you suffered the class cast exception in line 8. Now look at the Java7 version of the same code:-Now, you can use boxing rather than writing new Integer(). So try inserting this line as before:-
list.add(123); // boxed to Integer object
And the compiler will complain. Remember the compiler error is your friend. The more compiler errors, the fewer runtime errors.

As for readability, you don't need to remember what the List contains. It says it there: <String>.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have (I hope) answered part of your question but not necessarily all of it.
You can have methods which take particular types by parametrising them.
 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Campbell. I am unclear on what they mean when they say programmers can implement generic algorithms.

Also, thanks to your example, I think I now understand how generic types are useful for datastructures like lists and maps. But aside from the collection classes, where would I use parameterised types? Could there be instances where parameterised types could come in handy for classes that I write?

Thanks,
Prasanna
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get all sorts of examples in the newer classes in Java8. Look at Stream or one of the Consumer classes.

You can create a method which takes a particular type of parameter
public <T> void foo(T t) {...}
… and be confident that whatever T you pass will be preserved throughout the execution of the method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!