I am confused by the way arrays work. If I pass an array reference to some method, then that method is able to change the index values previously stored in array. However, if do the same with, say, a wrapper class object then that method is not able to change the value. Here is the code:
public class TestArray {
public static void main(String[] args) {
ChangeValues ch=new ChangeValues();
int intArr[]={1,2,3};
Integer iWrapper=new Integer(123);
ch.changeArray(intArr);
for(int i:intArr){
System.out.print(i);// o/p: 789
}
System.out.println("\n-----------------");
ch.changeWrapper(iWrapper);
System.out.println(iWrapper);// o/p: 123
}
}
class ChangeValues{
void changeArray(int i[]){
i[0]=7;
i[1]=8;
i[2]=9;
}
void changeWrapper(Integer i){
i=789;
}
}
output:
789
-----------------
123
Why is it that an array is able to change and not wrapper object. can any one clear away my doubts? thanks.
Instead of using the Integer wrapper, use something like this (note that auto-boxing will be broken, so it will have to be done manually):
public class MyInteger {
private int intValue;
public MyInteger(int val) {
intValue = val;
}
public void setValue(int val) {
intValue = val;
}
pubic int intValue() {
return intValue;
}
}
Then your changeWrapper
method can be:
void changeWrapper(MyInteger i){
i.setValue(789);
}
And
ch.changeWrapper(iWrapper);
System.out.println(iWrapper.intValue());
Will print "789".
Alternatively, you could make intValue
public:
public int intValue;
And then your changeWrapper method could become:
void changeWrapper(MyInteger i){
i.intValue = 789;
}
This is effectively what an array is -- an object with a whole bunch of public fields.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다