Java 泛型与通配符 定义与使用

2023-05-08,,

一、泛型

    定义

    把类型明确的工作推迟到创建对象或调用方法时才明确的类型,简而言之,未明确的数据类型
    类型:

    泛型类,泛型方法,方形接口。
    格式

泛型类格式:class 类名<E变量>{}
泛型方法格式:修饰符 <泛型> 返回值类型 方法名(参数列表(使用泛型))
泛型接口格式:修饰符 interface 接口名<>

    使用:
泛型类:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
} }
泛型方法:
public class WideType {
public static void main(String[] args) {
WideType m=new WideType();
m.method(1);
m.method("倪妮");
m.method(true);
m.method(8.8);
System.out.println("--------");
method2(8);
method2("蔡卓亦的微笑");
method2(9.9);
method2("l love java");
}
public <E> void method(E e){
System.out.println(e);
}
public static <E> void method2(E e){
System.out.println(e);
}
}
泛型接口:
public interface Iterator<E> { boolean hasNext(); E next();
}

二、通配符

    定义:

    代表任意的数据类型;不能创建对象使用,只能在方法中使用
    使用

public static void main(String[] args) {
ArrayList<String> list=new ArrayList<>();
list.add("倪妮");
list.add("真漂亮!");
list.add("feel");
ArrayList<Integer> list3=new ArrayList<>();
list3.add(2);
list3.add(0);
print(list);
print(list3);
}
public static void print(ArrayList<?> list2){
Iterator<?> it=list2.iterator();
while(it.hasNext()){
Object next = it.next();
System.out.println(next);
}
}

Java 泛型与通配符 定义与使用的相关教程结束。

《Java 泛型与通配符 定义与使用.doc》

下载本文的Word格式文档,以方便收藏与打印。