[英]How to convert Java primitive to boxed type in IntelliJ Structural Replace
[英]A reference to primitive type in Java (How to force a primitive data to remain boxed)
我想將一個原始類型的引用傳遞給一個方法,它可能會改變它。
請考慮以下示例:
public class Main {
Integer x = new Integer(42);
Integer y = new Integer(42);
public static void main(String[] args) {
Main main = new Main();
System.out.println("x Before increment: " + main.x);
// based on some logic, call increment either on x or y
increment(main.x);
System.out.println("x after increment: " + main.x);
}
private static void increment(Integer int_ref) {
++int_ref;
}
}
運行示例的輸出是:
x Before increment: 42
x after increment: 42
這意味着int_ref是按值傳遞給函數的,而不是通過引用,盡管我的名字很樂觀。
顯然有一些方法可以解決這個特定的例子,但我的實際應用程序更復雜,一般來說,人們可以想象一個“指針”或對整數的引用在許多場景中都會有用。
我試圖將Object傳遞給函數(然后轉換為int),以及各種其他方法,沒有運氣。 似乎有效的一種解決方法是定義我自己的Integer類版本:
private static class IntegerWrapper {
private int value;
IntegerWrapper(int value) { this.value = value; }
void plusplus() { ++value; }
int getValue() { return value; }
}
這樣做,並傳遞對IntegerWrapper的引用確實按預期工作,但根據我的口味,它似乎非常蹩腳。 來自C#,盒裝變量只是盒裝,我希望我能錯過一些東西。
編輯:
我認為我的問題不是Java“傳遞參考”或“傳遞價值”的重復嗎? 因為我的問題不是理論問題,因為我只是尋求解決方案。 從哲學上講,所有語言中的所有方法調用都是按值傳遞:它們要么傳遞實際值,要么通過值傳遞值。
所以,我會重新解釋一下我的問題:解決這個問題的常見范例是什么,在java中我無法傳遞對Integer的引用。 上面提到的IntegerWrapper是一個已知的范例嗎? 庫中是否存在類似的類(可能是MutableInt)? 也許一個長度為1的數組是一種常見的做法並且具有一些性能優勢? 我是唯一一個因為他可以存儲任何類型對象的引用而煩惱的人,但基本類型?
正如您可能注意到的, Integer
是不可變的。
private static class IntegerWrapper
是正確的。 使用大小為1的數組也是正確的,但實際上我從未見過在這種情況下使用數組。 所以請使用IntegerWrapper.
您可以在Apache org.apache.commons.lang3.mutable.MutableInt
找到完全相同的實現。
在您的示例中,您還可以向靜態方法提供Main
實例:
public class Main {
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
incrementX(main);
}
private static void incrementX(Main main) {
main.x++;
}
}
最后,從Java8開始,您可以定義一個inc
函數並使用它來增加值:
public class Main {
private static final IntFunction<Integer> INC = val -> val + 1;
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
main.x = INC.apply(main.x);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.