简体   繁体   中英

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.

           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.

Strings in Java are immutable so all operations on the string return a new copy.

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. 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 = name.toUpperCase();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM