[英]Custom number class to be used as out parameter
Java 中没有“out”或“ref”参数(我可能错了,因为我在 3 年内没有接触过 Java。)。 我正在考虑创建类,如 MyInteger、MyFloat 和 MyDouble,用作输出参数。 有没有办法将它们组合成一个通用 class?
MyInteger class 的示例代码:
public class MyInteger
{
private int value = 0;
public int getValue(){ return value;}
public void setValue(int newValue) {value = newValue;}
}
编辑:
如何使用 MyInteger class:
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、... 组合成一个通用的 class。
您可以使用 AtomicInteger、AtomicLong、AtomicReference 等。它们完全按照您的建议进行操作,并且作为附加功能,它们是高度线程安全的
并回应此评论:
但是为什么没有 AtomicFloat 和 AtomicDouble
这是java.util.concurrent.atomic
package JavaDocs所说的:
此外,仅为那些在预期应用程序中通常有用的类型提供类。 例如,没有用于表示
byte
的原子 class 。 在您希望这样做的罕见情况下,您可以使用AtomicInteger
来保存字节值,并进行适当的转换。 您还可以使用Float.floatToIntBits
和Float.intBitstoFloat
转换来保持浮点数,并使用Double.doubleToLongBits
和Double.longBitsToDouble
转换来保持双精度。
我自己的看法:这听起来非常复杂,我会用 go 和AtomicReference<Double>
, AtomicReference<Float>
等代替
除了out参数有点尴尬,我不推荐它们,你为什么不使用Integer
之类的?
由于它们都扩展了Number
你可以这样做:
public class MyNumber<T extends Number>
{
private T value = null;
...
}
恕我直言,如果您正确使用对象/访问者模式,则永远不需要从方法返回多个值。
返回包含多个值的 object
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);
或者您可以更新调用 object 方法,而不是返回值。
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);
你可以让你的新类子类编号。 Integer、Float 等是不可变的唯一原因是因为它们就是这样实现的。
或者,您可以创建一个您传递的 NumberHolder class,它有一个可变的 Number 字段。
class NumberHolder {
private Number num;
public void setNumber(Number num) {
this.num = num;
}
public void getNumber() {
return num'
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.