Home Java javaTutorial Detailed explanation of sample code of java generics

Detailed explanation of sample code of java generics

Mar 21, 2017 am 10:19 AM

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)
Copy after login

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)前面不需要再进行强制类型转换。
Copy after login

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 List.class or List.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
Copy after login

(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 <>.

For example: T get() method declaration becomes Object get(); List 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的抽象方法,明显错误,因此编译器的巨大作用就是在这里帮忙生成了该方法,同时编译器也依靠该功能完成检错任务。
}
Copy after login

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
Copy after login

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
Copy after login

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异常,提高了代码重用率
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles