Last active
March 8, 2018 03:39
-
-
Save HYChou0515/468c24bf0f3d76ffd1135dcc6c31692e to your computer and use it in GitHub Desktop.
Will the method change the primitive, instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
int[] array=new int[3]; | |
array[0]=0; | |
array[1]=3; | |
array[2]=6; | |
printarray(array); | |
something1(array); //not change | |
printarray(array); | |
something2(array); //change | |
printarray(array); | |
System.out.println(); | |
int x = 10; | |
System.out.println(x); | |
something(x);// not change | |
System.out.println(x); | |
System.out.println(); | |
Integer y = new Integer(11); | |
System.out.println(y); | |
something(y);// not change | |
System.out.println(y); | |
System.out.println(); | |
Obj m = new Obj("59381",10); | |
m.print(); | |
something1(m); // not change | |
m.print(); | |
something2(m);// change | |
m.print(); | |
} | |
private static void something(int x){ | |
x=19; | |
} | |
private static void something(Integer x){ | |
x=new Integer(98); | |
} | |
private static void something1(int[] array){ | |
array=new int[3]; | |
array[0]=9; | |
array[1]=8; | |
array[2]=7; | |
} | |
private static void something2(int[] array){ | |
array[0]=100; | |
} | |
private static void printarray(int[] array){ | |
for(int i:array){ | |
System.out.print(i+" "); | |
}System.out.println(); | |
} | |
private static void something1(Obj m){ | |
m = new Obj("999",11); | |
} | |
private static void something2(Obj m){ | |
m.setArray("432"); | |
m.setNum(99); | |
} | |
} | |
class Obj { | |
private int[] array; | |
private int num; | |
public Obj(String s, int n){ | |
array = new int[s.length()]; | |
for(int i = 0; i < s.length(); i++){ | |
array[i] = s.charAt(i)-'0'; | |
} | |
num = n; | |
} | |
public void print(){ | |
for(int i:array){ | |
System.out.print(i+" "); | |
}System.out.println(); | |
System.out.println(num); | |
} | |
public void setArray(String s){ | |
array = new int[s.length()]; | |
for(int i = 0; i < s.length(); i++){ | |
array[i] = s.charAt(i)-'0'; | |
} | |
} | |
public void setNum(int n){ | |
num = n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changing member of array, member of instance inside the method will affect them outside
Changing the address of array, address instance inside will not affect them outside.