Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics doubt

 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test3 {

public static void main(String[] args) {
show(new Integer[]{1,23,12});
showObj(new Integer[]{1,23,12});
}

static <E> void show(E[] inputArray) {
for(E element : inputArray) {
System.out.println(element);
}
}

static void showObj(Object[] obj) {
for(Object o : obj) {
System.out.println(o);
}
}
}
in the above code, both show(),showObj() is giving the same result.
what significance generics method adds to the code.
Please explain the reason behind going for generics.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sentil kumar:
...Please explain the reason behind going for generics.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked.

Ref: Sun - Generics.
 
Allan Jacobs
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics are especially useful when using collections. When using collections, the use of generics serves as an assertion that all the members of a collection have the same or at least a compatible set of types.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic