Você está na página 1de 13

USING

GENERIC IN
JAVA, WHY AND
WHERE

Martin Nad martinnad@ymail.com


generic using in java and why

USING GENERIC IN JAVA AND WHY, WHERE

HISTORY

For the first time this concept used in Ada in 1983, it allows you to use
the same functions or types for different data types.
Using generic in programming help you to maintenance easier and
reduce you source code.
For those people that have worked with C++ and are familiar with C+
+, the generic type in Java is similar with the Template in C++ with
some differences.
It allows you to define a class or function and use it for every different
data types.
Generic wasn’t possible before java 5, I usually used data type of
Object to use some similarly Template functionality in earlier java
version, which it wasn’t without problem. We will see some example
here and see why the data-type of Object doesn’t work.
And typically example is using List.
I will describe more about it in this paper.

TEMPLATE IN C++
An example on how you can use template in c++ can be:

template <typename T>


class Queue
{
std::vector<T> data;

Page 2
generic using in java and why

public:
void Add(T const &d);
void Remove();
void Print();
};

As you can see you can add integer, string, or other data type in this
Queue-system .
you can use exactly the same class and use class instead typename.

WHY USING GENERIC

As I want show you by example later, Generics are checked at compile-


time for type.
By using “type erasure” process, the generic type information should
remove, if we have some ArrayList<String>, it will be converted to the
non-gernric type ArrayList (raw type).
In the compile-time, it check the code and guarantee that the type is
correct.

ADVANTAGES TO USING GENERIC

-it checks in compile-time not run-time.


-You can define one class, function and use for every data type.

Page 3
generic using in java and why

And you shouldn’t thin about what happened in compiler, but if you
curious, the compiler just generate for the data type that you have
used it.
It should be very easier to debug and it reduce your code line.

You can use Template / Generic approach mostly for implement of


containers such as lists, hash table and for some sorting algorithm. In
those cases you need some more general approach than a certain data
type or type.

Page 4
generic using in java and why

Generic using in java and


why
[TYPE THE SUBTITLE]

JAVATM LANGUAGE SPECIFICATION:

A type variable is an unqualified identifier. Type variables are


introduced by generic class declarations, generic interface
declarations, generic method declarations, and by generic constructor
declarations.
A class is generic if it declares one or more type variables. These type
variables are known as the type parameters of the class. It defines one
or more type variables that act as parameters. A generic class
declaration defines a set of parameterized types, one for each possible
invocation of the type parameter section. All of these parameterized
types share the same class at runtime.
An interface is generic if it declares one or more type variables. These
type variables are known as the type parameters of the interface. It
defines one or more type variables that act as parameters. A generic
interface declaration defines a set of types, one for each possible
invocation of the type parameter section. All parameterized types
share the same interface at runtime.
A method is generic if it declares one or more type variables. These
type variables are known as the formal type parameters of the

Page 5
generic using in java and why

method. The form of the formal type parameter list is identical to a


type parameter list of a class or interface.
A constructor can be declared as generic, independently of whether
the class the constructor is declared in is itself generic. A constructor is
generic if it declares one or more type variables. These type variables
are known as the formal type parameters of the constructor. The form
of the formal type parameter list is identical to a type parameter list of
a generic class or interface.

WHY YOU SHOULD USING GENERIC IN JAVA

Now I want to look at some example to clear why we should use


Generic in JAVA.
If we look at the following code, what’s happened in following code:
List list = new ArrayList();
list.add("some value");
Integer i = (Integer)list.get(0);
In Line 1 you have use the ArrayList of type Object.

And in line 2, you assigned a String to arrayList.

And finally in line3, you cast of value list.get(0) to integer, which is not valid.

The complier shouldn’t generate any Error, but in runtime you will get an exception on
line three for classcastException (java.lang.classcastexception).

To avoid this kind of runtime-error you can use the Generic as follows:

List<String> list = new ArrayList<String>();


list.add("some value");
Integer i = list.get(0);

Page 6
generic using in java and why

Here you will get an error in compile time, not in runtime.

In line 1, you declares the ArrayList of string.


In line 2, you add some value.
In line 3, you assigned the list.get(0) to integer, which is not correct
and you will get a complier error.
This was a one of the reasons to use Generic

ADVANTAGES OF GENERIC IN JAVA

One the most important of advantages of Generic in Java is, you can
use the wildcards to define your type of parameters by just a question
mark “?”.

For example if you use <?> instead in example above, it means that
the datatype is unknown and function of this type of parameter can get
any type of list, regardless of parameter’s type. One thing you should
remember that, the function return Object-type. And the second you
should remember that none-null elements are not allowed used with
Generic.

You can use the extend keyword to define the upper bound of a
Generic Element as follows:
List <? Extend Number>, and means that List can be float, integer or
class Number, and it will return the Number. You should remember
that you cannot convert from a type to an other type, since it sounds
that float and integer are sub type of Number.
And exactly at the same way, if you want define the lower bound of a
Generic Element you can use the super keyword as follows:

Page 7
generic using in java and why

List<? super Number>


And it means that this List represent of Number and Object, and the
function will return always Object. And it requires Number or its
subclasses.

AN EXAMPLE

If we look at the following example we can see better how we can use
Generic in Java.
There are two files, on interface and on implementation of interface.
I have just make a very simple interface which it has just one function,
and it will print out the type of class we define or use in our
application.

package martin.test.generic.example2;

public interface GetClassType<M> {


public void printClassType(M type);

And here is the code:


As you can see I have made a instance of this class and use it for
String, and when we write out the type of class, it will show it is String,

Page 8
generic using in java and why

And in the second case I made a new object of the same class and give
it Integer as parameter and when we look at the type of the class, it
will show it is Integer.
Very simple you can use and make you own define classes and
function by using Generic.

///////////////////////////////////////////////
package martin.test.generic.example2;

public class MainGetClassType<M> implements GetClassType<M>


{

/**
* @param args
*/
public static void main(String[] args) {
MainGetClassType<String> mainGetClassType = new
MainGetClassType<String>();
mainGetClassType.printClassType(new String("test"));
mainGetClassType.printClassType();

MainGetClassType<Integer> mainGetClassType2 = new


MainGetClassType<Integer>();
mainGetClassType2.printClassType(new Integer(4));
mainGetClassType2.printClassType();

Page 9
generic using in java and why

public void printClassType(M type) {


System.out.println(type.getClass());

}
public void printClassType() {
System.out.println(this.getClass());

An other example for class definition

package martin.test.generic.example3;

public class GenericTest3 <O, T, M>{

public GenericTest3(O o, T t, M m){

one = o;

two = t;

three = m;

public O getOne(){

return one;

public T getTwo(){

return two;

Page 10
generic using in java and why

public M getThree;

public String toString(){

return one.toString()+" "+two.toString()+" "+three.toString()+"\n";

private O one;

private T two;

private M three;

package martin.test.generic.example3;

public class MainGenericTest3 {

/**

* @param args

*/

public static void main(String[] args) {

GenericTest3<String, String, String> genericTest3StringString =

new GenericTest3<String, String, String>("StringA", "StringB",


"StringC");

GenericTest3<String, Integer, String> genericTest3StringInteger =

new GenericTest3<String, Integer, String>("String",


100,"Integer");

System.out.println("StringStringString:" +
genericTest3StringString.toString());

System.out.println("StringIntegerString:" +
genericTest3StringInteger.toString());

Page 11
generic using in java and why

HOW TO USE GENERIC IN FUNCTION

It is very simple, you can define as usual function as follows

Public List<String> stringList(List s){


Return <String>s;
}

Or in our example:
Public GenericTest3<String, String, String> test(String s1, String s2,
String3){
Return new GenericTest3<String, String, String>(s1,s2,s3);
}
or
Public GenericTest3<String, Integer, String> test(String s1, Integer i1,
String3){
Return new GenericTest3<String, String, String>(s1,i1,s3);
}

To be continue….

Page 12
generic using in java and why

Properties in Java and Spring by Martin Nad


Spring and Cxf by Example
Jboss and Perm Gen Error
Using Ftp Service With Spring
JunIt
How to use Maven
ReFactoring
Maven and Custome Archetype
How to Write Effective Code
Using Generic in Java Why and where
Java Caching
what is new in java 5

Page 13

Você também pode gostar