실제로 내가 아는 한 Java 언어 에는 ref 또는 out 키워드 가 없습니다 . 그러나 저는 매개 변수 를 사용 하는 Java 로 C # 코드를 변환했으며 방금 수행 한 작업을 조언합니다. 어떤 객체 든 래퍼 클래스로 래핑하고 다음과 같이 래퍼 객체 인스턴스에 래핑 된 값을 전달해야합니다.
래퍼 사용에 대한 간단한 예
다음은 래퍼 클래스입니다 .
public class Wrapper {
public Object ref1; // use this as ref
public Object ref2; // use this as out
public Wrapper(Object ref1) {
this.ref1 = ref1;
}
}
그리고 여기에 테스트 코드가 있습니다.
public class Test {
public static void main(String[] args) {
String abc = "abc";
changeString(abc);
System.out.println("Initial object: " + abc); //wont print "def"
Wrapper w = new Wrapper(abc);
changeStringWithWrapper(w);
System.out.println("Updated object: " + w.ref1);
System.out.println("Out object: " + w.ref2);
}
// This won't work
public static void changeString(String str) {
str = "def";
}
// This will work
public static void changeStringWithWrapper(Wrapper w) {
w.ref1 = "def";
w.ref2 = "And this should be used as out!";
}
}
실제 사례
out 매개 변수를 사용하는 AC # .NET 메서드
여기에 out 키워드를 사용 하는 C # .NET 메서드가 있습니다 .
public bool Contains(T value)
{
BinaryTreeNode<T> parent;
return FindWithParent(value, out parent) != null;
}
private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
BinaryTreeNode<T> current = _head;
parent = null;
while(current != null)
{
int result = current.CompareTo(value);
if (result > 0)
{
parent = current;
current = current.Left;
}
else if (result < 0)
{
parent = current;
current = current.Right;
}
else
{
break;
}
}
return current;
}
out 매개 변수를 사용하는 C # 코드에 해당하는 Java
그리고 래퍼 클래스 의 도움으로이 메서드에 해당 하는 Java 는 다음과 같습니다.
public boolean contains(T value) {
BinaryTreeNodeGeneration<T> result = findWithParent(value);
return (result != null);
}
private BinaryTreeNodeGeneration<T> findWithParent(T value) {
BinaryTreeNode<T> current = head;
BinaryTreeNode<T> parent = null;
BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
resultGeneration.setParentNode(null);
while(current != null) {
int result = current.compareTo(value);
if(result >0) {
parent = current;
current = current.left;
} else if(result < 0) {
parent = current;
current = current.right;
} else {
break;
}
}
resultGeneration.setChildNode(current);
resultGeneration.setParentNode(parent);
return resultGeneration;
}
래퍼 클래스
그리고이 자바 코드에서 사용되는 래퍼 클래스 는 다음과 같습니다.
public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>> {
private BinaryTreeNode<TNode> parentNode;
private BinaryTreeNode<TNode> childNode;
public BinaryTreeNodeGeneration() {
this.parentNode = null;
this.childNode = null;
}
public BinaryTreeNode<TNode> getParentNode() {
return parentNode;
}
public void setParentNode(BinaryTreeNode<TNode> parentNode) {
this.parentNode = parentNode;
}
public BinaryTreeNode<TNode> getChildNode() {
return childNode;
}
public void setChildNode(BinaryTreeNode<TNode> childNode) {
this.childNode = childNode;
}
}