JAVA Generics

1. What is Generics? 

Generics allow for parameterised types — for example, an instance of the Vector class can be declared to be a vector of strings (written Vector<String>) — and hence allow the compiler to enforce type safety. To avoid major changes to the Java run-time environment, generics are implemented using a technique called type erasure. This is equivalent to removing the additional type information and adding casts where required.

2. Type parameter

List<Object> list

3. Type erasure

Java Generics implementation realized based on compiler layer, there is no generics type parameter info. in java byte code. Type parameter in generics is removed when java class compile, this is called type erasure.

For example,  List<Object> and List<String> are compiled to List.  Type parameter is not visible for JVM.  This mechanism is useful to find potential run time error when compile.

There are many characteristics related to type erasure:

  • There is no class object for genericss. For example, no List<String>.class or List<Integer>.class.
  • Generics class instances share all the static variable. For MyClass<T> class, use MyClass.myStaticVar to get the static variable.
  • Generics can not be used in Java catch. For exceptions are handled when code run.

The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.


List v = new ArrayList();

v.add("test");

Integer i =(Integer)v.get(0); // Run time error

Although the code compiles without error, it throws a runtime exception(java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.


Using generics, the above code fragment can be rewritten as follows:

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

v.add("test");

Integer i = v.get(0);// (type error) Compile time error


The type parameter String within the angle brackets declares the ArrayList to be constituted of String(a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值