[英]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.