Home  >  Article  >  Java  >  Detailed explanation of sample code of java generics

Detailed explanation of sample code of java generics

黄舟
黄舟Original
2017-03-21 10:19:491588browse

This article mainly introduces the relevant knowledge of java generics. Has very good reference value. Let's take a look at it with the editor

First of all, please look at the following code:

public class generictype {
 public static void main(String str[]) {
  Hashtable h =new Hashtable();
  h.put(1, "String类型");
  int a = (String) h.get(1);
  System.out.println(a);
 }
}
//执行结果
String类型
//如果我们将上述由红色标出的String改为int执行后结果如下(更改后编译没有错误):
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
 at genetictype.generictype.main(generic1.java:10)

The above is a typical example of what forced type conversion may bring Error, however this error cannot be known during compilation, so that a type conversion exception is thrown after jvm check during runtime.

Look at the following code again:

public class generictype { 
 public static void main(String str[]) {  
 Hashtable<Integer, String> h = new Hashtable<Integer, String>();
  h.put(1, "String类型");
  String a= h.get(1);
  System.out.println(a);
 }
}
//执行结果
string类型
//需要提出的是1.上述由红色标出的String如果改为int,在编译的时候会报错
   2.在h.get(1)前面不需要再进行强制类型转换。

In summary, the role of generics is:

1. It is checked during compilation Type safety (solve the errors that may be caused by forced type conversion in Java) has given the compiler a huge mission.

2. Improve code reuse rate

Type erasure:

Type erasure means that when the compiler compiles the .java file, the class If the generic parameters are removed, the generics will not be visible when the jvm loads the bytecode file. This process is called type erasure.

Phenomena related to type erasure:

(1) The generic class does not have the class type of Class. For example, there is no Listf7e83be87db5cd2d9a8a0b8117b38cd4.class or Listc0f559cc8d56b43654fcbe4aa9df7b4a.class, but only List.class.

(2) staticVariables are shared by all instances of the generic class.

public class generictype 
{
 public static void main(String str[]){
  test1<String> t = new test1<String>();
  test1<Date> tt = new test1<Date>();
  System.out.println(t.a);
  System.out.println(tt.a);
 }
}
class test1<T>{
 static int a = 1;
}
//结果
1

(3) Generic type parameter errors cannot pass Exception handling, because exception handling is implemented by jvm, and jvm loads The bytecode file has erased the generic features, which also indirectly illustrates the meaning of generics: parameter type errors were found during compilation.

The basic process of type erasure is also relatively simple:

1. Replace the type parameters with the top-level parent class, which is generally Object , if an upper bound for the type parameter is specified, this upper bound is used.

2. Remove the type declaration that appears, that is, remove the content of a8093152e673feb7aba1828c43532094.

For example: T get() method declaration becomes Object get(); Listf7e83be87db5cd2d9a8a0b8117b38cd4 becomes List. Next, you may need to generate some bridge methods. This is because the class after erasing the type may lack some necessary methods. For example, consider the following code:

public class generictype {public static void main(String str[]) {
  test3 t =new test3();
   t.getT("11111");
 }
}
interface test2<T>{
 public T getT(T t);
}
class test3 implements test2<String>{
 public String getT(String t){
  return t;
 }
}
//类型擦除后的代码
public class generictype {
 public static void main(String str[]) {
  test3 t = new test3();
  t.getT("11111");
 }
 interface test2 {
  public Object getT(Object t);
 }
 class test3 implements test2 {
 public String getT(String T){
   return T }
 public Object getT(Object t) {
  return this.getT((String) t);
  }//如果没有这段代码,在类型擦除后test3没有重写接口test2的抽象方法,明显错误,因此编译器的巨大作用就是在这里帮忙生成了该方法,同时编译器也依靠该功能完成检错任务。
}

Classification of generics: generic classes, generic interfaces, generic methods, generic exceptions

Generic class

public class generictype {
 public static void main(String str[]) {
  test<Integer, String> t = new test<Integer, String>();
  t.put(1, "str1");
  t.put(2, "str2");
  System.out.println(t.get(1));
  System.out.println(t.get(2));
 }
}
class test<T, V> {
 public Hashtable<T, V> h = new Hashtable<T, V>();
 public void put(T t, V v) {
  h.put(t, v);
 }
 public V get(T t) {
  return h.get(t);
 }
}
//执行结果
str1
str2

Polymorphic method (generic method): Define generics before the function name Parameters can be passed in the parameter list, return value type, and method body Reference

public class generictype {
public <T> String getString(T obj){
 return obj.toString();
}
 public static void main(String str[]) {
  generictype g =new generictype ();//不需要类的泛型
  System.out.println(g.getString(1));
  System.out.println(g.getString(&#39;a&#39;));
  System.out.println(g.getString("a"));
 }
}
//执行结果
a
a

Generic exception (both generic interface)

public class generictype {
 public static void main(String str[]) {
 TestException t =new TestException();
 try {
  t.excute(2);
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
}
//extends说明该泛型参数继承于Exception
interface TestExceptionInterface<T extends Exception>
{
 public void excute(int i) throws T;
}
class TestException implements TestExceptionInterface<IOException>{
 @Override
 public void excute(int i) throws IOException {
 if(i<10){
  throw new IOException();
 }
 }
}
//意义:1.针对不同的可能出现的异常类型,定义自己的实现类。
  2.定义多个实现类的时候,不用一个一个手动throws异常,提高了代码重用率

The above is the detailed content of Detailed explanation of sample code of java generics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn