[Java notes] generics, generic wildcards, variable parameters

1. Generic

1. Overview of Generics

Everyone observe the following code:

public class GenericDemo {
    
    
    public static void main(String[] args) {
    
    
        Collection coll = new ArrayList();
        coll.add("abc");
        coll.add("itcast");
        coll.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放
        Iterator it = coll.iterator();
        while(it.hasNext()){
    
    
            //需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
            String str = (String) it.next();//java.lang.ClassCastException
            System.out.println(str.length());
        }
    }
}

There was a problem java.lang.ClassCastException when the program was running . Why does a type conversion exception occur? Let's analyze it: because any type of element in the collection can be stored. Causes a ClassCastException at runtime to be forced to be taken out. How to solve this problem? Although Collection can store various objects, in fact, Collection only stores objects of the same type. For example, they are storing string objects. Therefore, after JDK5, a new generic ( Generic ) grammar has been added, allowing you to specify the class or method to support generics when designing the API, so that we can use the API more concisely and get the compile-time grammar an examination.
Insert picture description here

2. The benefits of generics

  • The ClassCastException in the runtime is transferred to the compile time and it becomes a compile failure.
  • Avoid the trouble of type conversion.
public class GenericDemo2 {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("itcast");
//         list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
        // 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
    
    
            String str = it.next();
            //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
            System.out.println(str.length());
        }
    }
}

3. The definition of generics

(1) Generic class

  • format:修饰符 class 类名<代表泛型的变量> { }
  • example:public class Generic<T>{ }

Determine generics when creating objects

public class Generic <T>{
    
    
    private T t;

    public T getT() {
    
    
        return t;
    }

    public void setT(T t) {
    
    
        this.t = t;
    }
}
public class GenericDemo3 {
    
    
    public static void main(String[] args) {
    
    
        Generic<String> g1 = new Generic<String>();
        g1.setT("林青霞");
        System.out.println(g1.getT());

        Generic<Integer> g2 = new Generic<Integer>();
        g2.setT(30);
        System.out.println(g2.getT());

        Generic<Boolean> g3 = new Generic<Boolean>();
        g3.setT(true);
        System.out.println(g3.getT());
    }
}

(2) Generic method

  • format:修饰符 <代表泛型的变量> 返回值类型 方法名(参数){ }
  • example:public <T> void show(T t){ }

When calling the method, determine the type of the generic

public class Generic2 {
    
    
    public <T> void show(T t){
    
    
        System.out.println(t);
    }
}
public class GenericDemo4 {
    
    
    public static void main(String[] args) {
    
    
        Generic2 g = new Generic2();
        g.show("张三");
        g.show(11);
        g.show(true);
    }
}

(3) Generic interface

  • format:修饰符 interface接口名<代表泛型的变量> { }
  • example:public interface MyGenericInterface<E>{ }
public interface MyGenericInterface<E>{
    
    
	public abstract void add(E e);
	
	public abstract E getE();  
}

1. Determine the type of generic when defining the class

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

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

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

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

	@Override
	public E getE() {
    
    
		return null;
	}
}
public class GenericInterface {
    
    
    public static void main(String[] args) {
    
    
        MyImp2<String>  my = new MyImp2<String>();  
        my.add("aa");
    }
}

Two. Generic wildcard

Type wildcard

  • Format :类型名称 <?> 对象名称
  • Meaning :此类型的元素可以匹配任何类型

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

        getElement1(list1);
        getElement1(list2);//报错
        getElement1(list3);
        getElement1(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){
    
    }

Three. Variable parameters

Insert picture description here

public class Args {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(sum(1,2));
        System.out.println(sum(1,2,3,4,5));
        System.out.println(sum(1,2,3,4,5,6,7,8));
    }
    public static int sum(int...a){
    
    
        int sum=0;
        for (int i:a){
    
    
            sum+=i;
        }
        return sum;
    }
}

Use of variable parameters

Insert picture description here

[Java Notes] Series

Guess you like

Origin blog.csdn.net/Supreme7/article/details/107085636
Recommended