I have basic class :
public class SomeClass {
private List<String> list = new ArrayList<String>();
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
In a method I have this code :
private void test(){
SomeClass sc1 = new SomeClass();
sc1.getList().add("a");
sc1.getList().add("b");
SomeClass sc2 = sc1;
System.out.println(sc2.getList().size());
sc1.getList().remove(0);
System.out.println(sc2.getList().size());
sc1=null;
System.out.println(sc2.getList().size());
sc2=null;
System.out.println(sc2.getList().size());
}
I receive :
- 2
- 1
- 1
- NullPointerException
but I though I would received :
- 2
- 1
- NullPointerException
- NullPointerException (if previous NullPointerException caught)
If a referenced object is set to null, the reference link is broken ? Thank you for clarifications
There’s no such concept as setting an object to null, You can only set a variable to null. This statement:
… changes the value of
sc1and that is all.A variable is simple a storage location with a name. The storage location has a value, and for variables whose type is non-primitive, that value is a reference. It’s very important to understand that the value of the variable is not an object. It’s just a reference.
So this statement:
just declares a new variable (
sc2) which starts off with the same value as an existing variable (sc1). The two variables are completely separate – they just happen to have the same value to start with.I like to think of variables as pieces of paper. A piece of paper can have some primitive value on it, such as a number, or it can have a house address1. Imagine these steps:
sc1)sc1onto another piece of paper (sc2)sc1sc2That’s similar to what you’re doing here… and clearly rubbing out the value on
sc1doesn’t affect either the house or thesc2piece of paper.Now as for why you see 2 and then 1… imagine these steps:
sc1)sc1to find the house, and put two parcels on the doorstepsc1onto another piece of paper (sc2)sc1to find the house, and shout out how many parcels you findsc1to find the house, and take one parcel awaysc2to find the house, and shout out how many parcels you findThe first time you’ll shout 2, and then you’ll shout 1. You’re not changing the values on the pieces of paper – you’re changing the house itself, by adding or removing parcels.
1 I know that references aren’t memory addresses necessarily. This is purely for the sake of the analogy, which is one I’ve found helpful.