如何在 Java 中使用等效于 C++ 的引用参数? [英] How do I use an equivalent to C++ reference parameters in Java?

查看:25
本文介绍了如何在 Java 中使用等效于 C++ 的引用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 C++ 中有这个:

Suppose I have this in C++:

void test(int &i, int &j)
{
    ++i;
    ++j;
}

这些值在函数内部被改变,然后在外部使用.我怎么能写出在 Java 中做同样事情的代码?我想我可以返回一个封装了这两个值的类,但这看起来真的很麻烦.

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

推荐答案

使用包装器模拟引用.

可以以某种方式模拟这种行为的一种方法是创建一个通用包装器.

Simulating reference with wrappers.

One way you can have this behavior somehow simulated is create a generic wrapper.

public class _<E> {
    E ref;
    public _( E e ){
        ref = e;
    }
    public E g() { return ref; }
    public void s( E e ){ this.ref = e; }

    public String toString() {
        return ref.toString();
    }
}

我不太相信这段代码的价值,因为我无法帮助它,我不得不编写代码 :)

I'm not too convinced about the value of this code, by I couldn't help it, I had to code it :)

原来是这样.

示例用法:

public class Test {

    public static void main ( String [] args ) {
        _<Integer> iByRef = new _<Integer>( 1 );
        addOne( iByRef );
        System.out.println( iByRef ); // prints 2

        _<String> sByRef = new _<String>( "Hola" );
        reverse( sByRef ); 
        System.out.println( sByRef ); // prints aloH

    }

    // Change the value of ref by adding 1
    public static void addOne( _<Integer> ref ) { 
        int i = ref.g();
        ref.s( ++i  );

        // or 
        //int i = ref.g();
        //ref.s( i + 1 );

    }
    // Reverse the vale of a string.
    public static void reverse( _<String> otherRef ) { 
        String v = otherRef.g();
        String reversed = new StringBuilder( v ).reverse().toString();
        otherRef.s( reversed );
    }

}

这里有趣的是,通用包装类名称是_",它是一个有效的类标识符.所以声明如下:

The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier. So a declaration reads:

对于整数:

_<Integer> iByRef = new _<Integer>( 1 );

对于字符串:

_<String> sByRef = new _<String>( "Hola" );

对于任何其他类

_<Employee> employee = new _<Employee>( Employee.byId(123) );

方法s"和g"代表设置和获取:P

The methods "s" and "g" stands for set and get :P

这篇关于如何在 Java 中使用等效于 C++ 的引用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆