• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics  RSS feed

 
nicky priya
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello every one , I want to know why generics are used in Java.
 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pretty broad question but I'll give you a simplified illustration:

If you write what kind of things (types) can you put in list?  Well, anything -- that is, any Object.  Now say you put two element of type Horse and three of type Bagel.  When you access list, how will you know if it's a Horse or a Bagel?

Generics protects you from this.  Now you write list can only contain objects of the type Horse.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple of things: better type safety and improved semantics.

Better type safety is illustrated in Knute's example. Before generics, you had to be very careful about the kind of objects that were in a List. Programmers had to know what was in a list so they could properly cast the objects to more specific types when they needed to use them.

With generics, you don't have to use casts to assure the compiler that you know what you're doing with the objects obtained from a collection. The compiler could make many of the necessary checks and automatically flag dangerous and obviously incorrect code. That meant that many programming errors could be caught at compile time instead of at runtime.

This in turn made programs clearer and more understandable (to a degree). List<Integer> carries more meaning than List and establishes the kind of things you can do with elements of a list declared that way.
 
nicky priya
Greenhorn
Posts: 28
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. Now i got a clear view of Generics.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!