some tips on java programming

1.
Bounded types are especially useful when you need to ensure that one type parameter is compatible with another. For example, consider the following class called Pair, which stores two objects that must be compatible with each other:

class Pair<T, V extends T> {
    T first;
    V second;

    Pair(T a, V b) {
      first = a;
      second = b;
        }

// This is OK because both T and V are Integer.
Pair<Integer, Integer> x = new Pair<Integer, Integer>(1, 2);
// This is OK because Integer is a subclass of Number.
Pair<Number, Integer> y = new Pair<Number, Integer>(10.4, 12);
However, the following is invalid:
// This causes an error because String is not
// a subclass of Number
Pair<Number, String> z = new Pair<Number, String>(10.4, "12");

2.Bounded Wildcards

In general, to establish an upper bound for a wildcard, use the following type of wildcard
expression:
<? extends superclass>
where superclass is the name of the class that serves as the upper bound. Remember, this is an
inclusive clause because the class forming the upper bound (that is, specified by superclass) is
also within bounds.
You can also specify a lower bound for a wildcard by adding a super clause to a wildcard
declaration. Here is its general form:
<? super subclass>
In this case, only classes that are superclasses of subclass are acceptable arguments. This is an
exclusive clause, because it will not match the class specified by subclass.
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值