有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

要用作out参数的java自定义数字类

Java中没有“out”或“ref”参数(我可能错了,因为我已经三年没有接触过Java了)。我想创建一些类,比如MyInteger、MyFloat和MyDouble,用作out参数。有没有办法将它们组合成一个泛型类

MyInteger类的示例代码:

public class MyInteger
{
   private int value = 0;

   public int getValue(){ return value;}
   public void setValue(int newValue) {value = newValue;}

}

编辑:

如何使用MyInteger类:

public boolean aMethod(int input, MyInteger output)
{
   boolean status = true;
   //calculation here;
   //set status to false if anything wrong;
   //if nothing wrong do this: output.setValue(newValue);
   return status;
}

编辑2:

我想问的是我希望我能结合MyInteger,MyFloat。。。变成一个泛型类


共 (1) 个答案

  1. # 1 楼答案

    IMHO,如果您正确地使用了对象/访问者模式,那么您永远不需要从一个方法返回多个值

    返回包含多个值的对象

    public Pair<Integer, Double> method3();
    

    或者使用访问者接收多个值。如果你能找出许多错误,这很有用

    public interface Visitor {
        public void onValues(int i, double d);
        public void onOtherValues(double d, String message);
    }
    
    method(Visitor visitor);
    

    或者,您可以更新调用的对象方法,而不是返回值

    public void method() {
        this.i = 10;
        this.d = 100.0;
    }
    

    例如

    Worker worker = new Worker();
    worker.method();
    int i = worker.i;
    double d = worker.d;
    

    也可以根据条件返回有效值

    // returns the number of bytes read or -1 on the end of the file.
    public int read(byte[] bytes);
    
    // index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1)
    public int binarySearch(Object[] array, Object key);
    

    有一个通用的持有者,你可以使用AtomicReference

    public void method(AtomicReference<Integer> i, AtomicReference<Double> i);
    

    对于某些类型,有内置类型AtomicBoolean、AtomicInteger和AtomicLong

    public void method(AtomicBoolean flag, AtomicInteger len);
    // OR
    public boolean method(AtomicInteger len);
    

    也可以使用普通数组

    int[] i = { 0 };
    double[] d = { 0.0 };
    method2(i, d);
    
    public void method2(int[] i, double[] d);