Home > Java > javaTutorial > body text

Java generics and wrapper class example analysis

王林
Release: 2023-04-21 19:19:06
forward
753 people have browsed it

1. What are generics?

The essence of generics is to parameterize types (without creating new types, to control the specific types of parameter restrictions through different types specified by generics) ).

Let’s look at the following example first:

The arrays we learned before can only store elements of specified types. For example: int[] array=new int[10];String[] array=new String[10];The Object class is the parent class of all classes, so can we create an Obj array?

class Myarray{
    public Object[] array=new Object[10];
    public void setVal(int pos,Object val){
        this.array[pos]=val;
    }
    public Object getPos(int pos){
        return this.array[pos];
    }
}
public class TestDemo{
    public static void main(String[] args) {
        Myarray myarray=new Myarray();
        myarray.setVal(1,0);
        myarray.setVal(2,"shduie");//字符串也可以存放
        String ret=(String)myarray.getPos(2);//虽然我们知道它是字符串类型,但是还是要强制类型转换
        System.out.println(ret);
    }
}
Copy after login

After the above code was implemented, we found:

  • Any type of data can be stored

  • No. 2 subscript It is originally a string, but it must be forced to type

to introduce generics. The purpose of generics is to specify what type of object the current container should hold and let the compiler Check it out yourself.

2. Generic syntax

class Generic class name{

//Type parameters can be used here

}

Use of generics:

Generic class Variable name=new Generic class(Constructor method actual parameters)

##MyArray list=new MyArray<>();

[Note]

  • The <> after the type represents a placeholder, indicating that the current class is a generic class

  • ##When instantiating a generic, <> cannot It is a simple type and needs to be a wrapper class
  • <>Type composition that does not participate in generics
  • cannot new generic types Array
  • Using generics does not require cast type conversion
  • A simple generic:
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型
public class Test<T>{ 
    //key这个成员变量的类型为T,T的类型由外部指定  
   private T key;
 
    public Test(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
        this.key = key;
    }
 
    public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
        return key;
    }
}
Copy after login

Erasure mechanism : The types in <> will be erased during compilation, so the things in <> will not participate in the composition of the type. Will erase T as Object.

Why can't an array of a generic type be instantiated?

An important difference between arrays and generics is how they enforce type checking. Arrays store and check type information at runtime, while generics check for type errors at compile time.

The returned Object array may store any type of data, such as string, which is received through an int type array. The compiler considers it unsafe.

3. Upper bound of generics

Syntax:

class generic class name{

}

Example:

public class MyArray{} //E can only be Number or a subclass of Number

public class MyArray>{}

//E must be a class that implements the Comparable interface

[Note] For E that does not specify a boundary, you can see For E extends Object

4, wildcard character

? For use in generics, it is a wildcard. Wildcards are used to solve the problem that anti-generic types cannot be covariant.

The following two pieces of code:

代码一:
public static<T> void printList1(ArrayList<T> list){
   for(T x:list){
      System.out.println(x);
   }
}
 
代码二:
public static<T> void printList2(ArrayList<?> list){
   for(Object x:list){
      System.out.println(x);
   }
}
Copy after login

Wildcards are used in code 2. Compared with code 1, we are not clear about the specific data type passed into code 1 at this time.

(1) Upper bound of wildcard character

Syntax:

//The actual parameter type that can be passed in is Number or a subclass of Number

Example: For the following relationship, we need to write a method to print a list that stores Animal or Animal subclasses.

Animal
Cat extends Animal

Dog extends Animal

Code 1:
public static <t extends Animal> void print1(List<T> list>{
    for(T animal:list){
        System.out.println(animal);//调用了T的toString
    }
}
Copy after login

At this time the T type is a subclass of Animal or yourself.

Code 2: Implemented through wildcards

public static void print2(List<? extends Animal> list){
    for(Animal animal:list){
       Syatem.out.println(animal);//调用了子类的toString方法
    }
}
Copy after login

The difference between the two codes:

##For methods implemented by generics, imposes restrictions on T, which can only be a subclass of Animal. Pass in Cat, it’s Cat.
  • For methods implemented by wildcards, it is equivalent to stipulating Animal and allowing subclasses of Animal to be passed in. The specific subcategory is not clear at this time. For example: when Cat is passed in, the declared type is Animal. Only by using polymorphism can the toString method of Cat be called.
  • ## Wildcard upper bound→ Parent-child class relationship:

//You need to use wildcards to determine the parent and child types

MyArrayList is the parent class of MyArrayList or MyArrayList

MyArrayList is MyArrayList< ;? extends Number>'s parent class

 ArrayList<Integer> arrayList1 = new ArrayList<>();
 ArrayList<Double> arrayList2 = new ArrayList<>();
 List<? extends Number> list = arrayList1;
 //list.add(1,1);//报错,此时list的引用的子类对象有很多,再添加的时候,任何子类型都可以,为了安全,java不让这样进行添加操作。
 Number a = list.get(0);//可以通过
 Integer i = list.get(0);//编译错误,只能确定是Number子类
Copy after login

[Note]

cannot be added to it. What is stored in the list may be Number or Number A subclass of which the type cannot be determined.

  • The wildcard upper bound is suitable for reading but not for writing.

  • (2) Lower bound of wildcard

  • Syntax:

< ? super Integer>//The parameter type that can be passed in is Integer or the parent class of Integer

The parent-child class relationship of the wildcard lower bound:

MyArrayList是MyArrayList的父类类型

MyArrayList<?>是MyArrayList的父类

通配符下界适合写入元素,不适合读取。

5、包装类

在Java中,由于基本类型不是继承自Object,为了在泛型中可以支持基本类型,每个基本类型都对应了一个包装类。除了Integer和Character,其余基本类型的包装类都是首字母大写。

拆箱和装箱:

int i=10;
 
//装箱操作,新建一个Integer类型对象,将i的值放入对象的某个属性中
Integer ii=i;  //自动装箱
//Integer ii=Integer.valueOf(i);
Integer ij= new Integer(i);//显示装箱
 
//拆箱操作,将Integer对象中的值取出,放到一个基本数据类型中
int j=ii.intValue();//显示的拆箱
int jj=ii;//隐式的拆箱
Copy after login

The above is the detailed content of Java generics and wrapper class example analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.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