C++ References and Java References

后端 未结 4 1525
忘了有多久
忘了有多久 2020-12-30 08:06

//C++ Example

#include 
using namespace std;

int doHello (std::string&);
int main() {
    std::string str1 = \"perry\";
    cout <<         


        
4条回答
  •  庸人自扰
    2020-12-30 08:23

    Java does not have pass by reference (which you were using in the C++ code) at all. The references are passed by value. (The values of str and str1 aren't objects at all, they're references - it really helps to keep the two concepts very separate.)

    Typically you would use a return value to return a new reference if you need to:

    str1 = doHello(str1);
    

    Note that String is slightly different to List etc, because strings are immutable. To modify a collection (well, any mutable collection) you don't need to create a new one, you just modify the object via the original reference:

    public static void addHello(List items)
    {
        items.add("Hello");
    }
    

    You could then call this like so:

    List list = new ArrayList();
    addHello(list);
    System.out.println(list.get(0)); // "Hello"
    

    The difference between mutating an existing object and changing the value of a variable to refer to a different object is crucial. If you want to leave the existing collection alone and create a new one, you'd have to do that explicitly:

    public static List withHello(List items)
    {
        List newList = new ArrayList(items);
        newList.add("Hello");
        return newList;
    }
    

    You'd then call it like this:

    List empty = new ArrayList();
    List newList = withHello(empty);
    System.out.println(empty.size()); // Prints 0
    System.out.println(newList.size()); // Prints 1
    

    Does this answer everything you needed?

提交回复
热议问题