通配符的使用

简介: 通配符的使用

2 通配符的使用
我们需要的解决方案:可以接收所有的泛型类型,但是又不能够让用户随意修改。这种情况就需要使用通配符"?"来处理

public static void main(String[] args) {

    Data<Integer> data = new Data<>();
    data.setData(10);
    print(data);
    Data<String> data1 = new Data<>();
    data1.setData("woyaojindachang");
    print(data1);
}
//此处?代表可以接受任意类型,但由于类型不确定,所以无法修改
public static void print(Data<?> data) {
    System.out.println(data.getData());
}

1
2
3
4
5
6
7
8
9
10
11
12

3 通配符的上界
? extends 类:设置泛型上限

class Data {

public T data;

public T getData() {
    return this.data;
}

public void setData(T data) {
    this.data = data;
}

}
public class Test {

public static void main(String[] args) {
    Data<Integer> data = new Data<>();
    data.setData(10);
    print(data);
    Data<String> data1 = new Data<>();
    data1.setData("woyaojindachang");
    print(data1);//String不属于Number的子类
}
public static void print(Data<? extends Number> data) {
    System.out.println(data.getData());
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

这里我们设置通配符的上界为Number,所以无法传入String。

因为此时通配符里可以接受任意类型,由于类型不确定,所以无法修改。

public static void print(Data<? extends Number> data) {

    Number number = data.getData();
}

1
2
3
因为data存储的是Number和它的子类,所以可以进行读取数据。

4 通配符的下界
? super 类:设置泛型下限

public static void fun(Data<? super Integer> data) {

    data.setData(10);
}

1
2
3
可以传入的实参的类型是Integer或者Integer的父类类型,此处可以修改,因为添加的是Integer或者它的父类。

但不能接收,因为无法确定是那个父类。

四、拆箱和装箱
手动装拆箱:

public static void main(String[] args) {

    //装箱
    Integer a = Integer.valueOf(10);
    Integer b = new Integer(10);
    //拆箱
    int c = a.intValue();
}

1
2
3
4
5
6
7
每次手动装拆箱太过于麻烦,系统提供自动装拆箱。

public static void main(String[] args) {

    //自动装箱
    Integer a = 10;
    Integer b = (Integer)10;
    //自动拆箱
    int j = a;
    int k = (int)a;
}

1
2
3
4
5
6
7
8

我们打开字节码看一下,发现系统自动在编译阶段调用了Integer.valueof和Integer.intValue方法

public static void main(String[] args) {

    Integer a = 127;
    Integer b = 127;
    Integer c = 200;
    Integer d = 200;
    System.out.println(a == b);
    System.out.println(c == d);
}

1
2
3
4
5
6
7
8
经典面试题
上面这段代码会输出什么呢?

我们可以发现当数值在一定的范围内时,返回的是固定引用,只有超出范围才会new 新对象。

我们可以得出 i 是介于-128 - 127之间的。

cache数组存储着这些引用,并且final不可修改。
Byte、Short、Integer、Long这四种包装类型默认创建了[-128,127]的相应类型缓存数据,Character创建了数值在[0,127]范围的缓存数据,Boolean直接返回true或者false。

相关文章
|
数据安全/隐私保护
正则表达式大全
正则表达式
69 3
|
5月前
使用正则表达式
使用正则表达式。
91 1
|
新能源 Java Linux
你必须掌握的常用正则表达式大全
你必须掌握的常用正则表达式大全
1490 1
你必须掌握的常用正则表达式大全
|
JavaScript 数据安全/隐私保护
|
编译器 测试技术 C++
正则表达式_1
b站:奇乐编程 10分钟快速掌握正则表达式
121 1
正则表达式_1
正则表达式(全)
正则表达式是由一些具有特殊含义的字符组成的字符串,多用于查找、替换符合规则的字符串。在表单验证、Url映射等处都会经常用到。
209 0
|
机器学习/深度学习 C# Windows