簡體   English   中英

void ref方法中的Java參考變量

[英]java reference variable in void ref method

我試圖弄清楚如何在void ref方法中訪問sb變量。 可能嗎? 我准備測試時出現了這個問題。

public class X{
  public void ref(String refStr, StringBuilder refSB){
    refStr = refStr + refSB.toString();
    refSB.append(refStr);
    refStr = null;
    refSB = null;
    //how can I access main variable sb here?  Not possible?
    //sb.append(str);
  }
  public static void main(String[] args){
    String s = "myString";
    StringBuilder sb = new StringBuilder("-myStringBuilder-");
    new X().ref(s, sb);
    System.out.println("s="+s+" sb="+sb);
  }
}

您正在為參考值分配一個null ,這使其指向無處。 傳遞參數時,將通過引用(內存指針)傳遞它。 分配新值或null更改引用,但不會更改它指向的內存對象。

因此,您可以在方法中使用StringBuilder ,它將更改保留在方法之外,但是您不能將其他內容分配給指針(因為指針本身是方法的局部變量)。

例如:

public static void ref (StringBuilder refSB) {
  refSB.append("addedWithinRefMethod");  // This works, you're using the object passed by ref
  refSB = null;  // This will not work because you're changing the pointer, not the actual object
}

public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  ref(sb);
  System.out.println(sb.toString());  // Will print "addedWithinRefMethod".
}

為了使代碼能夠執行您想要的操作,您需要再使用一次引用,例如使用數組:

public static void ref(StringBuilder[] refSB) {
  refSB[0] = null;  // This works, outside the method the value will still be null
}

public static void main(String[] args) {
  StringBuilder[] sb = new StringBuilder[] { new StringBuilder() };
  ref(sb);
  System.out.println(sb[0]);  // Will print "null"
}

但是,請記住,副作用(一種更改其外部定義的對象的方法)通常被認為是不好的做法,並在可能的情況下避免使用。

是的,可以在void ref()方法中使用sb引用。您實際上是使用new X().ref(s, sb);sb引用傳遞給ref() new X().ref(s, sb); 而在

 public void ref(String refStr, StringBuilder refSB){
    refStr = refStr + refSB.toString();
    refSB.append(refStr);
    refStr = null;

    //USe refSB variable here
    refSB.append(str);
  }

不要這樣做refSB = null;.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM