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 List
(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 .
For example: T get() method declaration becomes Object get(); List
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('a')); 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!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use
