[英]Changing a Linked List with a method
I thought that method can't change an object in java directly, but as I see I was wrong. 我以为该方法不能直接在Java中更改对象,但是正如我所知,我错了。
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
String name = "Boycie";
add(5, list);
add(2, list);
add(3, list);
for(Integer integer:list){
System.out.print(integer + " ");
}
toUpperCase(name);
System.out.println(name);
}
public static void add(int number, LinkedList<Integer> list){
list.add(number);
}
public static void toUpperCase(String name){
name.toUpperCase();
}
Would someone explain me why does method work for Linked List, but it doesn't for string object? 有人可以解释一下为什么方法对链接列表有效,但对字符串对象无效吗? I thought it wouldn't work for list either, and that I'd need to have a method of return type LinkedList as I would do for String.
我以为它也不能用于列表,并且我需要像String一样具有返回类型LinkedList的方法。
Strings in Java are immutable so all operations on the string return a new copy. Java中的字符串是不可变的,因此对该字符串的所有操作都返回一个新副本。
So you can do as below to get the results you expect: 因此,您可以执行以下操作以获得期望的结果:
LinkedList<Integer> list = new LinkedList<>();
String name = "Boycie";
add(5, list);
add(2, list);
add(3, list);
for (Integer integer : list) {
System.out.print(integer + " ");
}
String newName = toUpperCase(name);
System.out.println(name);
System.out.println(newName);
}
public static void add(int number, LinkedList<Integer> list) {
list.add(number);
}
public static String toUpperCase(String name) {
return name.toUpperCase();
}
In java if u pass a variable as an argument, it always passes the referrence/memory location, thus if u change the value inside a method, the original value will also be changed. 在Java中,如果您将变量作为参数传递,则它始终会传递引用/内存位置,因此,如果您在方法内部更改了值,原始值也将被更改。 Thats why the linked list is changing.
这就是为什么链接列表正在更改。 Now for the string, name.toUpperCase() will return a new string containing the uppercase version of the source string, ie it will not change the original string.. to change the orifinal string, use the following
现在对于字符串,name.toUpperCase()将返回一个新字符串,其中包含源字符串的大写版本,即它不会更改原始字符串。要更改原始字符串,请使用以下命令
name = name.toUpperCase(); 名称= name.toUpperCase();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.