Java에서 기본 요소에 대한 참조에 의한 전달과 동등한 작업을 수행하는 방법
이 자바 코드 :
public class XYZ {   
    public static void main(){  
        int toyNumber = 5;   
        XYZ temp = new XYZ();  
        temp.play(toyNumber);  
        System.out.println("Toy number in main " + toyNumber);  
    }
    void play(int toyNumber){  
        System.out.println("Toy number in play " + toyNumber);   
        toyNumber++;  
        System.out.println("Toy number in play after increement " + toyNumber);   
    }   
}  
다음과 같이 출력됩니다.
놀이 5 장난감 번호 기소 6 이후 놀이 장난감 번호 메인 5의 장난감 번호
C ++에서는 toyNumber섀도 잉을 방지하기 위해 참조에 의한 전달로 변수를 전달할 수 있습니다. 즉, 아래와 같은 동일한 변수의 복사본을 생성합니다.
void main(){  
    int toyNumber = 5;  
    play(toyNumber);  
    cout << "Toy number in main " << toyNumber << endl;  
}
void play(int &toyNumber){  
    cout << "Toy number in play " << toyNumber << endl;   
    toyNumber++;  
    cout << "Toy number in play after increement " << toyNumber << endl;   
} 
C ++ 출력은 다음과 같습니다.
놀이 5 장난감 번호 기소 6 이후 놀이 장난감 번호 메인 6의 장난감 번호
내 질문은 -Java가 참조로 전달하는 것이 아니라 값으로 전달되는 경우 C ++ 코드와 동일한 출력을 얻기 위해 Java에서 동등한 코드는 무엇입니까 ?
몇 가지 선택이 있습니다. 가장 의미있는 것은 당신이하려는 일에 달려 있습니다.
선택 1 : toyNumber를 클래스의 공용 멤버 변수로 만들기
class MyToy {
  public int toyNumber;
}
그런 다음 MyToy에 대한 참조를 메서드에 전달하십시오.
void play(MyToy toy){  
    System.out.println("Toy number in play " + toy.toyNumber);   
    toy.toyNumber++;  
    System.out.println("Toy number in play after increement " + toy.toyNumber);   
}
Choice 2: return the value instead of pass by reference
int play(int toyNumber){  
    System.out.println("Toy number in play " + toyNumber);   
    toyNumber++;  
    System.out.println("Toy number in play after increement " + toyNumber);   
    return toyNumber
}
This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.
Choice 3: make it a class or static variable
If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.
Choice 4: Create a single element array of type int and pass that
This is considered a hack, but is sometimes employed to return values from inline class invocations.
void play(int [] toyNumber){  
    System.out.println("Toy number in play " + toyNumber[0]);   
    toyNumber[0]++;  
    System.out.println("Toy number in play after increement " + toyNumber[0]);   
}
Java is not call by reference it is call by value only
But all variables of object type are actually pointers.
So if you use a Mutable Object you will see the behavior you want
public class XYZ {
    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }
    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}
Output of this code:
run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)
You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.
    List<Integer> mutableList = new ArrayList<Integer>();
    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);
    System.out.println(mutableList);
    Collections.shuffle(mutableList);
    System.out.println(mutableList);
    Collections.sort(mutableList);
    System.out.println(mutableList);
Output of this code:
run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)
Make a
class PassMeByRef { public int theValue; }
then pass a reference to an instance of it. Note that a method that mutates state through its arguments is best avoided, especially in parallel code.
For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:
import java.util.concurrent.atomic.AtomicInteger;
public class PrimitivePassByReferenceSample {
    /**
     * @param args
     */
    public static void main(String[] args) {
        AtomicInteger myNumber = new AtomicInteger(0);
        System.out.println("MyNumber before method Call:" + myNumber.get());
        PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
        temp.changeMyNumber(myNumber);
        System.out.println("MyNumber After method Call:" + myNumber.get());
    }
     void changeMyNumber(AtomicInteger myNumber) {
        myNumber.getAndSet(100);
    }
}
Output:
MyNumber before method Call:0
MyNumber After method Call:100
You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.
In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.
public static void main(String[] args) {
    int[] toyNumber = new int[] {5};
    NewClass temp = new NewClass();
    temp.play(toyNumber);
    System.out.println("Toy number in main " + toyNumber[0]);
}
void play(int[] toyNumber){
    System.out.println("Toy number in play " + toyNumber[0]);
    toyNumber[0]++;
    System.out.println("Toy number in play after increement " + toyNumber[0]);
}
'IT박스' 카테고리의 다른 글
| Java 8이 값이나 기능을 반복하는 좋은 방법을 제공합니까? (0) | 2020.08.09 | 
|---|---|
| JavaScript에서 regex \ S는 무엇을 의미합니까? (0) | 2020.08.09 | 
| SMTP를 사용하여 Python에서 메일 보내기 (0) | 2020.08.09 | 
| PHP에서 int의 최대 값은 얼마입니까? (0) | 2020.08.09 | 
| 특정 iPhone / iPod touch 모델 감지 (0) | 2020.08.09 |