A brief introduction to java generics and packaging classes

Generic

  • Generics : Unknown types can be used preemptively in classes or methods.

tips:
Generally, when creating an object, the unknown type is used to determine the specific type. When no generic type is specified, the default type is Object type.
Generics are a part of data types. We will combine class names and generics as data types.

Use of generics

Definition format:

修饰符 class 类名<代表泛型的变量> {  }

For example, the ArrayList collection in the API:

class ArrayList<E>{
    
     
    public boolean add(E e){
    
     }

    public E get(int index){
    
     }
   	....
}

Use generics: When to determine generics.

Determine generics when creating objects

E.g,ArrayList<String> list = new ArrayList<String>();

At this time, the value of variable E is of String type, then the ArrayList collection in the API can be understood as:

class ArrayList<String>{
    
     
     public boolean add(String e){
    
     }

     public String get(int index){
    
      }
     ...
}

For another example,ArrayList<Integer> list = new ArrayList<Integer>();

At this time, the value of variable E is of type Integer, then the ArrayList collection in the API can be understood as:

class ArrayList<Integer> {
    
     
     public boolean add(Integer e) {
    
     }

     public Integer get(int index) {
    
      }
     ...
}

Example custom generic class

public class MyGenericClass<MVP> {
    
    
	//没有MVP类型,在这里代表 未知的一种数据类型 未来传递什么就是什么类型
	private MVP mvp;
     
    public void setMVP(MVP mvp) {
    
    
        this.mvp = mvp;
    }
     
    public MVP getMVP() {
    
    
        return mvp;
    }
}

use:

public class GenericClassDemo {
    
    
  	public static void main(String[] args) {
    
    		 
         // 创建一个泛型为String的类
         MyGenericClass<String> my = new MyGenericClass<String>();    	
         // 调用setMVP
         my.setMVP("雷霆嘎巴");
         // 调用getMVP
         String mvp = my.getMVP();
         System.out.println(mvp);
         //创建一个泛型为Integer的类
         MyGenericClass<Integer> my2 = new MyGenericClass<Integer>(); 
         my2.setMVP(123);   	  
         Integer mvp2 = my2.getMVP();
    }
}

Contains generic methods

Definition format:

修饰符 <代表泛型的变量> 返回值类型 方法名(参数){  }

E.g,

public class MyGenericMethod {
    
    	  
    public <MVP> void show(MVP mvp) {
    
    
    	System.out.println(mvp.getClass());
    }
    
    public <MVP> MVP show2(MVP mvp) {
    
    	
    	return mvp;
    }
}

Use format: when calling a method, determine the type of generic

public class GenericMethodDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        MyGenericMethod mm = new MyGenericMethod();
        // 演示看方法提示
        mm.show("aaa");
        mm.show(123);
        mm.show(12.45);
    }
}

Contains generic interfaces

Definition format:

修饰符 interface接口名<代表泛型的变量> {  }

E.g,

public interface MyGenericInterface<E>{
    
    
	public abstract void add(E e);
	
	public abstract E getE();  
}

Use format:

1. Determine the type of generic when defining the class

E.g

public class MyImp1 implements MyGenericInterface<String> {
    
    
	@Override
    public void add(String e) {
    
    
        // 省略...
    }

	@Override
	public String getE() {
    
    
		return null;
	}
}

At this time, the value of the generic E is of type String.

2. The type of generic is always uncertain, until the object is created, the type of generic is determined

E.g

public class MyImp2<E> implements MyGenericInterface<E> {
    
    
	@Override
	public void add(E e) {
    
    
       	 // 省略...
	}

	@Override
	public E getE() {
    
    
		return null;
	}
}

Identify generics:

/*
 * 使用
 */
public class GenericInterface {
    
    
    public static void main(String[] args) {
    
    
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa");
    }
}

Generic wildcard <?>

When using a generic class or interface, in the data passed, the generic type is uncertain, and wildcards can be used ?Said.
Note that once the generic wildcard is used, only the common methods in the Object class can be used, and the methods of the elements in the collection cannot be used.

How to use wildcards

Generic wildcard: When you don't know what type to use to receive data, you can use? To indicate unknown data. (? means unknown wildcard)

But at this time, only data can be accepted, and data cannot be stored in the collection.

For example, everyone can understand and use:

public static void main(String[] args) {
    
    
    Collection<Intger> list1 = new ArrayList<Integer>();
    getElement(list1);
    Collection<String> list2 = new ArrayList<String>();
    getElement(list2);
}
public static void getElement(Collection<?> coll){
    
    }
//?代表可以接收任意类型

There is no inheritance relationship between generics
: Collection<Object> list = new ArrayList<String>(); This is wrong.

Advanced use of wildcards-restricted generics

When setting generics before, it can actually be set arbitrarily, as long as it is a class. But in JAVA's generics, you can specify the upper and lower limits of a generic .

The upper limit of generics :

  • Format :类型名称 <? extends 类 > 对象名称
  • Meaning :只能接收该类型及其子类

The lower limit of generics :

  • Format :类型名称 <? super 类 > 对象名称
  • Meaning :只能接收该类型及其父类型

For example: now known Object class, String class, Number class, Integer class, where Number is the parent class of Integer

public static void main(String[] args) {
    
    
    Collection<Integer> list1 = new ArrayList<Integer>();
    Collection<String> list2 = new ArrayList<String>();
    Collection<Number> list3 = new ArrayList<Number>();
    Collection<Object> list4 = new ArrayList<Object>();
    
    getElement(list1);
    getElement(list2);//报错
    getElement(list3);
    getElement(list4);//报错
  
    getElement2(list1);//报错
    getElement2(list2);//报错
    getElement2(list3);
    getElement2(list4);
  
}
// 泛型的上限:此时的泛型?,必须是Number类型或者Number类型的子类
public static void getElement1(Collection<? extends Number> coll){
    
    }
// 泛型的下限:此时的泛型?,必须是Number类型或者Number类型的父类
public static void getElement2(Collection<? super Number> coll){
    
    }

Packaging

Basic objects are packed into objects,

Basic classes are highly efficient

The wrapper has more functions and can call methods.

basic type Corresponding packaging class (located in the java.lang package)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Automatic boxing and unboxing

Automatic boxing is to automatically convert basic data types to wrapper types;

Automatic unboxing is to automatically convert the wrapper type to the basic data type.

Since JDK1.5

Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);
i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5;
//加法运算完成后,再次装箱,把基本数值转成对象。

Basic type conversion to String

There are a total of three ways to convert the basic type to String. You can see from the information after class. Here we only talk about the simplest way:

基本类型直接与””相连接即可;如:34+""

static toString(parameter); toString() in the overloaded Object

static valueOf(parameter);

String is converted to the corresponding basic type

Except for the Character class, all other wrapper classes have parseXxx static methods that can convert string parameters into corresponding basic types:

  • public static byte parseByte(String s): Convert the string parameter to the corresponding byte basic type.
  • public static short parseShort(String s): Convert the string parameter to the corresponding short basic type.
  • public static int parseInt(String s): Convert the string parameter to the corresponding int basic type.
  • public static long parseLong(String s): Convert the string parameter to the corresponding long basic type.
  • public static float parseFloat(String s): Convert the string parameter to the corresponding float basic type.
  • public static double parseDouble(String s): Convert the string parameter to the corresponding double basic type.
  • public static boolean parseBoolean(String s): Convert the string parameter to the corresponding boolean basic type.

Code use (only the static method parseXxx of the Integer class as an example) such as:

public class Demo18WrapperParse {
    
    
    public static void main(String[] args) {
    
    
        int num = Integer.parseInt("100");
    }
}

Note: If the content of the string parameter cannot be correctly converted to the corresponding basic type, an java.lang.NumberFormatExceptionexception will be thrown .

Guess you like

Origin blog.csdn.net/ren9436/article/details/107583093