Java 泛型各种情况实例

Pair<String> p1 = new Pair<>("JR", "SM");
Pair<Employee> p2 = new Pair<>(new Employee("a", 10), new Employee("b", 20));
System.out.println(p1.getClass() == p2.getClass());

仅检查是否为 Pair 类型。

 

 

package com.learn.corejava.generic;

import java.time.LocalDate;

public class DateInterval extends Pair<LocalDate> {
    @Override
    public LocalDate getSecond() {
        return super.getSecond();
    }

    @Override
    public void setSecond(LocalDate second) {
        super.setSecond(second);
    }
}

此时在 DateInterval 中,有两个 getSecond 方法:

LocalDate getSecond();// 定义在DateInterval

Object getSecond(); // 定义在 Pair 中,被复写的方法。首次调用的桥方法

Object getSecond(); 会先调用,然后其会调用LocalDate getSecond();

 

Pair<String>[] tps = new Pair[10];
Pair<String> p = new Pair<>();
tps[0] = p;

上面代码是合法的。

Pair<String>[] tps = new Pair<String>[10];

非法代码:Generic array creation。

 

public static <T> void addAll(Collection<T> coll, T... ts) {
    for (T t : ts) {
        coll.add(t);
    }
}
Collection<Pair<String>> table = new ArrayList<>();
Pair<String> p1 = new Pair<>();
Pair<String> p2 = new Pair<>();
addAll(table, p1, p2);
System.out.println(table.size());

T...ts 其实是创建一个 Pair<String>数组。这违反了上面的规则,但在这种情况下是合法的。

 

 

不能实例化泛型类型。

new T(...). 的语法是错误的。

可以使用两种方法实现:

public static <T> Pair<T> makePair(Supplier<T> constr) {
    return new Pair<>(constr.get(), constr.get());
}

public static <T> Pair<T> makePair(Class<T> cl) {
    try {
        return new Pair<>(cl.newInstance(), cl.newInstance());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}
Pair<String> pair = Pair.makePair(String::new);
System.out.println(pair);

Pair<String> pair1 = Pair.makePair(String.class);
System.out.println(pair1);

 

 

在方法中构建泛型数组

public static <T extends Comparable> T[] minmax(IntFunction<T[]> constr, T... a) {
    T[] mm = constr.apply(2);
    T min = a[0];
    T max = a[0];
    for (T t : a) {
        if (t.compareTo(min) < 0) {
            min = t;
        }
        if (t.compareTo(max) >= 0) {
            max = t;
        }
    }

    mm[0] = min;
    mm[1] = max;
    return mm;
}
String[] mm = ArrayAlg.minmax(String[]::new, "JR", "RED", "GO", "JAVA");
System.out.println(Arrays.toString(mm));

Java1.8 以前方式

public static <T extends Comparable> T[] minmax(T... a) {
    T[] mm = (T[]) Array.newInstance(a.getClass().getComponentType(), 2);
    T min = a[0];
    T max = a[1];
    for (T t : a) {
        if (t.compareTo(min) < 0) {
            min = t;
        }
        if (t.compareTo(max) >= 0) {
            max = t;
        }
    }

    mm[0] = min;
    mm[1] = max;
    return mm;
}
String[] mm = ArrayAlg.minmax("JR", "RED", "GO", "JAVA");
System.out.println(Arrays.toString(mm));

 

不能应用到静态变量中

public class Singleton<T>{
    private static T singleInstance; // Error
    public static T getSingleInstance() {
        if (singleInstance == null) construct new instance of T
            return singleInstance;
    }
}
 

 

 

不能在异常处理中应用泛型

public class Problem<T> extends Exception { /* . . . */ } // Error--can't extend Throwable
 

public static <T extends Throwable> void doWork(Class<T> t)
{
try
{
do work
}
catch (T e) // Error--can't catch type variable
{
Logger.global.info(...)
}
}
 

需要捕获明确的异常类型

public static <T extends Throwable> void doWork(T t) throws T {
    try {
        // something.
    } catch (Throwable e) {
        t.initCause(e);
    }
}

 

public static void swap(Pair<?> p) {
    swapHelper(p);
}

public static <T> void swapHelper(Pair<T> p) {
    T t = p.getFirst();
    p.setFirst(p.getSecond());
    p.setSecond(t);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值