It might feel a little bit around to see the headline? Look at the following questions first! Recently in the Android project, the analysis of the data of a collection object is wrong, finally found the problem, to record, in fact, super-basic things, ╮(╯▽╰)╭
Private StaticArraylist<node> Mdatas =NULL;/** * @param args * * Public Static void Main(string[] args) {Arraylist<node> A =NewArraylist<node> (); Node na =NewNode (); Na.setdata (Ten); Na.setindex (0); Node NB =NewNode (); Nb.setdata ( One); Nb.setindex (1); A.add (NA); A.add (NB); R (a);//Call, think about the results? R (a);//Call again, think about the results? }Private Static void R(Arraylist<node> a) {SetData (a); System.out.println ("A's data length:"+ a.size ()); }Private Static void SetData(arraylist<node> Array) {if(Mdatas! =NULL) {mdatas.clear (); Mdatas =NULL; } Mdatas = array; System.out.println ("mdata Data length:"+ mdatas.size ()); }
The result is:
Data length of Mdata: 2
Data length of a: 2
Data length of Mdata: 0
Data length of a: 0
Are you right?
Maybe that's right, then you don't have to watch it? Maybe not to continue to look at the following code:
First declare a class:
Public classNode {Private intDataPrivate intIndex Public int GetData() {returnData } Public void SetData(intData) { This. data = data; } Public int GetIndex() {returnIndex } Public void Setindex(intIndex) { This. index = index; }}
Next, look at the main code:
Public Static void Main(string[] args) {//TODO auto-generated method stub /** * Set * *Arraylist<integer> a=NewArraylist<integer> (); Integer i1=1; Integer i2=2; A.add (I1); A.add (I2); Arraylist<integer> B=a; Arraylist<integer> c=b; C.clear (); System.out.println ("The length of the collection:"+a.size ());/** * Array * * int[] in=New int[Ten]; in[0]=1; in[1]=2;int[] ou=in; ou[0]=0; System.out.println ("The first element of the array in:"+in[0]); System.out.println ("Array in second element"+in[1]);/** * Custom Object * *Node na=NewNode (); Na.setdata (1); Na.setindex (0); Node Ba=na; Ba.setdata (2); System.out.println ("na data equals:"+na.getdata ()); }
In fact, the above code is very simple, is to declare an object first, and then declare a variable of the object type, and then let other variables get the object's reference. For example: B=a,c=b, if a Java foundation should know thatB or C obtains the address of a reference object, Operation B or C is to manipulate the object directly. so the result:
Length of collection: 0
The first element of the array in: 0
Array in second element 2
The data of Na equals: 2
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Issues raised by references to Java reference types