Home > Java > javaTutorial > What are generics in Java? Detailed introduction to Java generics

What are generics in Java? Detailed introduction to Java generics

不言
Release: 2018-10-19 16:28:53
forward
3710 people have browsed it

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

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

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

}

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

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

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);

}
Copy after login

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

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

The class that implements the generic interface...

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

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

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);
    }

}
Copy after login

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> {

}
Copy after login

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template