Java - replace() method using values from arrays is changing the array values?

后端 未结 1 1309
难免孤独
难免孤独 2021-01-26 01:12

I\'m doing something like

public static String[] list = {\"a\",\"b\",\"c\",\"d\",}  //It gives me a NullPointeException if I didn\'t use static
public String en         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-26 01:54

    I suspect your question is "why is chaining .replace acting oddly" and the array is not changing. You can prove that replace does not change the array quite easily:

        System.out.println(Arrays.toString(list));
        encrypt("abc");
        System.out.println(Arrays.toString(list));
    

    So what is going on with your code? Each time you replace a letter you end up with a new string, that again you replace letters on. I don't have your full source code so I'll show with a real simple version:

    a = a.replace("a", "b");
    a = a.replace("b", "c");
    a = a.replace("c", "d");
    

    For "abc" is.... 'ffffd'.

    The answer to this is to look at each letter at a time and change it. Loop through the string and create a new one.

    0 讨论(0)
提交回复
热议问题