Home  >  Article  >  Java  >  Let’s understand generics in Java together

Let’s understand generics in Java together

WBOY
WBOYforward
2022-05-18 17:06:462039browse

This article brings you relevant knowledge about java, which mainly introduces issues related to generics, including custom generic classes, custom generic methods, custom Let’s take a look at generic interfaces and other contents. I hope it will be helpful to everyone.

Let’s understand generics in Java together

Recommended study: "java video tutorial"

  • Generics: is in JDK5 The introduced feature can constrain the data types of operations and check them at the compilation stage.
  • Format of generics:, note: generics can only support reference data types.
  • All interfaces and implementation classes of the collection system support the use of generics.

Advantages:

  • Unified data type.
  • Advance running problems to the compilation period to avoid possible problems with forced type conversion, because the type can be determined during the compilation stage.
public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("石原里美");
        list.add("工藤静香");
        list.add("朱茵");
        for (String s : list) {
            System.out.println(s);
        }
    }
输出结果:
石原里美
工藤静香
朱茵

And generics can be defined in many places, such as the generic class after the class, the generic method after the method declaration, and the generic interface after the interface. Next, let’s learn how to use these generics together:

Custom generic class

Concept

  • Definition class A class that defines generics at the same time is a generic class.
  • Format of generic class: modifier class class name {   }
public class MyArrayList<E>{    }
  • Function: Can be used during compilation phase Specify the data type, similar to the role of a collection

Practical teaching

Now create a generic class to implement basic add and delete operations to learn more about its usage:

//泛型类MyArrayLIst
public class MyArrayLIst<E> {
    public void add(E e){

    }
    public void remove(E e){

    }
}
//main
public static void main(String[] args) {
        MyArrayLIst<String> list = new MyArrayLIst<>();
        //通过对泛型的设定,实现对数据专一处理
        list.add("石原里美");
        list.add("工藤静香");
        list.remove("工藤静香");
    }

Principle of generic classes:

Replace all occurrences of generic variables with the real data type transmitted.

Through careful observation, it is not difficult to find that the biggest difference between generic classes and ordinary classes is that the same data can be processed uniformly when calling methods, and other data types will not be involved. To a certain extent, problems that may arise during forced type conversion are avoided.

Custom generic method

Concept

  • A method that defines a generic method while defining a method is a generic method .
  • Format of generic method: Modifier return value type method name (formal parameter list) {    }
public <E> void view(E e){    }
  • Function: Generics can be used in methods to receive parameters of all actual types, making the method more versatile.
  • Note: Generic methods need to be distinguished from methods defined in generic classes. Although they are also using generics, the generics are not defined by them, but by generics. Class defined.

Practical teaching

No matter what type of array is passed in, its content can be returned, that is, the function of Arrays.toString() is realized

public static void main(String[] args) {
        String [] name = {"石原里美","工藤静香","朱茵"};
        view(name);
        Integer [] age = {18,19,20};
        view(age);
    }
    public static  <T> void view(T[] arr){
        StringBuilder list = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            list.append(arr[i]).append("\t");
        }
        System.out.println(list);
    }

Pass Implementing the definition of generic methods can realize the reception of multiple data types and have a wider range of applications.

Custom generic interface

Concept

  • The interface defined using generics is a generic interface.
  • Format of generic interface: public interface People{         }
  • ##
public interface People <E>{    }
    Function: Generic interface allows the implementation class to select the current The data type that the function needs to operate
Practical teaching

Define a People interface to implement operations on the Teacher class, Student class, etc.

//People接口
public interface People <E>{
    void run(E e);
    void height(E e);
}
//Student类
public class Teacher {

}
//实现类Fantype
public class Fantype implements People<Teacher> {

    @Override
    public void run(Teacher teacher) {

    }

    @Override
    public void height(Teacher teacher) {

    }
}
Through the above Observing the code, we can find that what type is defined after People, then the implementation class can only operate on this data type, and other types cannot perform this operation.

通配符和上下限 

通配符 

  • ?可以在“使用泛型”的时候代表一切类型
  • E T K V是在定义泛型的时候用的 

 假设现在有一场为学生和老师而举办的比赛,需要比较速度究竟谁更快,分别创建一定数量的对象并将其传入集合之中。然而当我们将这两个集合分别传入方法中的时候,会发现,学生对象集合list2出现报错,为什么呢?原因是因为数据类型不同,那么该如何使得两种类型都可以传入呢?或许这个时候就会有人说了:“既然两个类都是People的子类,那么为什么不定义它的泛型是People呢?”这个想法很好,但是我们需要明确一点的是子类与父类虽然是有关系的,但是定义之后的集合是没有关系的,所以这里是行不通的。

//main
//老师对象集合
ArrayList<Teacher> list1 = new ArrayList<>();
list1.add(new Teacher());
list1.add(new Teacher());
pk(list1);
//学生对象集合
ArrayList<Student> list2 = new ArrayList<>();
list2.add(new student());
list2.add(new student());
pk(list2);//由于pk方法的形参是泛型为Teacher的集合,所以会报错
//父类
class People{

    }
//子类
class Teacher extends People{

    }
class student extends People{

    }
//pk方法:
public static void pk(ArrayList<Teacher> people){
}

应对这个问题,我们可以便可以将本篇文章引入的知识“通配符”放在实际应用中解决问题了,通过其简短的概念“?可以在‘使用泛型’的时候代表一切类型”就可以理解其作用了,这里我们可以使用“?”共同代表两种类型。

public static void pk(ArrayList<?> people){
//通过通配符?便可以将这个问题解决掉
    }

 上下限 

然而此时又出现一个问题,定义了一个dog类,试图创建一些对象并传入集合中混入比赛,这种当然情况当然是不允许发生的,然而?是可以表示任意类型的,并不能对其进行限制。因此上下限的作用就体现出来了:

  •  上限:,传入类型必须是该父类或者是父类的子类
  • 下限:,传入类型必须是该子类或者是子类的父类
public static void pk(ArrayList<? extends People> people){
//通过上下限便可以将这个问题解决掉
//要求传入的类型必须是People的子类才可以
    }

推荐学习:《java视频教程

The above is the detailed content of Let’s understand generics in Java together. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete