Java - 在参数上进行更改而不返回新变量[重复]

问题描述 投票:-1回答:1

我试图在Java中的字符串中反转单词。它初始化为char数组。我尝试的方法是将其转换为String数组,进行更改,并将其转换回char数组。但是,即使我尝试将新数组引用到原始数组,也不会对作为参数传入的原始数组进行更改。当我们必须修改参数而不返回函数中的任何内容时,如何处理这种情况?谢谢。

public static void main(String[] args) {
    char[] s = new char[] {'t','h','e',' ','s','k','y',' ','i','s',' ','b','l','u','e'};
    reverseWords(s);
    System.out.println(s);
}

public static void reverseWords(char[] s) {
    String str = new String(s);
    String [] strArray = str.split(" ");

    int n = strArray.length;
    int begin;
    int end;
    int mid = (n-1)/2;

    for (int i=0; i<=mid; i++) {
        begin = i;
        end = (n-1) -i;
        String temp = strArray[begin];
        strArray[begin] = strArray[end];
        strArray[end] = temp;   
    }
    String s_temp =  Arrays.toString(strArray).replace("[", "").replace("]", "").replace(",", "");
    s = s_temp.toCharArray();
    System.out.println(s);
}
java pass-by-reference
1个回答
0
投票

你不能做s = ...

但是,您可以将字符插入现有的s数组中,调用者将看到更改的值。

替换这个:

s = s_temp.toCharArray();

有:

for(int i = 0; i < s_temp.length(); i++) {
    s[i] = s_temp.charAt(i);
}

或使用System.arraycopy()

© www.soinside.com 2019 - 2024. All rights reserved.