一.引用的介绍
引用:为对象起立另一个名字,引用类型引用另一种类型。
引用并非对象,相反的,它只是为一个已存在的对象所起的另外一个名字。
eg. ArrayList intList = new ArrayList();
- 这个 intList 不是对象本身,是对象的引用
- 右边的“new ArrayList”,是以ArrayList类为模板,在堆空间里创建一个ArrayList对象。
二.什么是引用
引用好比遥控器,对象好比电视机
三.引用的赋值
Student student1 = new Student("Jack");
Student student2 = new Student("Rose");
● new出来两个对象
● student1和student2是这两个对象的引用
提问: student1 = student2; //what heppened here?
举例:
class IntegerWrapper {
public int integer;
public IntegerWrapper(int value) {
this.integer = value;
}
}
public class Main {
public static void increment(int a) {
a++;
}
public static void increment(IntergerWrappper intw) {
intw.integer++;
}
public static void main(String []args){
int a = 10;
IntegerWrappper intw = new IntegerWrapper(10);
increment(a);
increment(intw);
System.out.println(a); //输出10
System.out.println(intw); //输出11 通过引用把这个引用指的对象的值给改变
}
}
总结:
● 传递引用 (其实是传递对象的地址)
● 修改引用所指向对象的数据则有变化,修改引用没有任何效果
四.引用的好处
● 引用存的是指向这个对象的地址
● 使得数据存储更加的整齐
● 需要专递引用去修改数据
五.特殊引用null
null :空的引用,没有引用任何对象。
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list = null; // list变成了空引用
list.add(1); // NullPointerException 空指针异常