search
HomeJavajavaTutorialWhat are generics in Java? Detailed introduction to Java generics

The content of this article is about what are generics in Java? The detailed introduction of Java generics has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What are generics?
Java generic design principles: As long as there are no warnings during compilation, there will be no ClassCastException exception during runtime.

Generics: work with clear types Delay the explicit special type until the time when creating the object or calling the method

Parameterized type:

The E in ArrayList is called the type parameter variable

The Integer in ArrayList is called the actual type parameter

The entire ArrayListgeneric type

The entire ArrayList is called the parameterized type ParameterizedType

2. Why are generics needed?

With generics:

  • The code is more concise [no forced conversion]

  • The program is more robust [As long as there are no warnings during compilation, there will be no ClassCastException exception during runtime]

  • Readability and stability [When writing a collection, The type is limited]

When creating the collection, we specify the type of the collection, so we can use enhanced for to traverse the collection!

//创建集合对象
ArrayList<string> list = new ArrayList();
list.add("hello");
list.add("world");
list.add("java");

//遍历,由于明确了类型.我们可以增强for
for (String s : list) {
    System.out.println(s);
}</string>

3. Basics of Generics
A generic class is to define the generic type on the class. When the user uses the class, the type is clarified... In this case, the user knows what type, This class represents what type... Users don't have to worry about forced transfer or runtime conversion exceptions when using it.

Generics defined on a class can also be used in class methods!

/*
    1:把泛型定义在类上
    2:类型变量定义在类上,方法中也可以使用
 */
    public class ObjectTool<t> {
        private T obj;
    
        public T getObj() {
            return obj;
        }
    
        public void setObj(T obj) {
            this.obj = obj;
        }
    }</t>

Which type the user wants to use, just specify the type when creating. When used, the class will automatically be converted into the type the user wants to use.

public static void main(String[] args) {

//创建对象并指定元素类型
ObjectTool<string> tool = new ObjectTool();

tool.setObj(new String("钟福成"));
String s = tool.getObj();
System.out.println(s);


//创建对象并指定元素类型
ObjectTool<integer> objectTool = new ObjectTool();
/**
 * 如果我在这个对象里传入的是String类型的,它在编译时期就通过不了了.
 */
objectTool.setObj(10);
int i = objectTool.getObj();
System.out.println(i);</integer></string>

}

Define generic methods.... Generics are defined first and then used

//定义泛型方法..
public <t> void show(T t) {
    System.out.println(t);
}</t>

What type is passed in by the user, what type is the return value?

public static void main(String[] args) {
    //创建对象
    ObjectTool tool = new ObjectTool();

    //调用方法,传入的参数是什么类型,返回值就是什么类型
    tool.show("hello");
    tool.show(12);
    tool.show(12.5);

}

The subclass clearly defines the type parameter variable of the generic class

/*
    把泛型定义在接口上
 */
public interface Inter<t> {
    public abstract void show(T t);
}</t>

The class that implements the generic interface...

/**
 * 子类明确泛型类的类型参数变量:
 */

public class InterImpl implements Inter<string> {
    @Override
    public void show(String s) {
        System.out.println(s);
    }
}</string>

4. Generic Application
When we write web pages, there are often multiple DAOs. We have to write several DAOs every time, which can be a bit troublesome.

public abstract class BaseDao<t> {

    //模拟hibernate....
    private Session session;
    private Class clazz;


    //哪个子类调的这个方法,得到的class就是子类处理的类型(非常重要)
    public BaseDao(){
        Class clazz = this.getClass();  //拿到的是子类
        ParameterizedType  pt = (ParameterizedType) clazz.getGenericSuperclass();  //BaseDao<category>
        clazz = (Class) pt.getActualTypeArguments()[0];
        System.out.println(clazz);

    }


    public void add(T t){
        session.save(t);
    }

    public T find(String id){
        return (T) session.get(clazz, id);
    }

    public void update(T t){
        session.update(t);
    }

    public void delete(String id){
        T t = (T) session.get(clazz, id);
        session.delete(t);
    }

}</category></t>

Inherits abstract DAO, and the implementation class has corresponding methods of adding, deleting, modifying and checking.

public class CategoryDao extends BaseDao<category> {

}
BookDao

public class BookDao extends BaseDao<book> {

}</book></category>

The above is the detailed content of What are generics in Java? Detailed introduction to Java generics. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools