C ++引用和Java引用 [英] C++ References and Java References

查看:115
本文介绍了C ++引用和Java引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// C ++范例

  #include< iostream> 
using namespace std;

int doHello(std :: string&);
int main(){
std :: string str1 =perry;
cout<< String =<< str1<< endl; $ b $ d doHello(str1);
cout<< String =<< str1<< endl; // prints pieterson
return 0;
}

int doHello(std :: string& str){
str =pieterson;
cout<< String =<< str<< endl;
return 0;
}

在上述情况下, str引用已修改



// Java示例

  public class hello {

public static void main(String args []){
String str1 =perry;
System.out.println(String =+ str1);
doHello(str1);
System.out.println(String =+ str1); //不打印pieterson
}

public static void doHello(String str){
str =pieterson;
System.out.println(String =+ str);
}
}



在Java中,String str和String str1是两个不同的对象最初引用相同的String,所以当我们改变doHello()中的str引用时,str1引用不会改变。



如何在Java中实现C ++风格的功能


$ b

更新

>感谢Jon的精彩解释,我相信任何Java初学者肯定会遇到这个问题。
让我解释一下在使用列表时遇到的问题。

  // bad doHello()

void doHello(List inputList){
inputList = getListFromAnyFunction(); //错误,没有工作
}

//好doHello

void doHello(List inputList){
inputList.addAll(getListFromAnyFunction()) ; //工作
}

感谢Powell和Harshath为您的解释和代码示例。 p>

解决方案

Java没有通过引用传递(你在C ++代码中使用)。引用通过值传递。 ( str str1 的值不是对象,它们是引用 - 这两个概念非常分开。)



通常,如果需要,您将使用一个返回值来返回一个新的引用:

  str1 = doHello(str1); 

请注意,String与List等稍有不同,因为字符串是不可变的。要修改集合(以及任何可变的集合),您不需要创建新集合,只需通过原始引用修改对象

  public static void addHello(List< String> items)
{
items.add(Hello);
}

您可以这样调用:

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

更改现有对象指向不同对象的变量的值是至关重要的。如果你想要离开现有的集合单独创建一个新的,你必须明确这样做:

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

您可以这样调用:

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

这是否能满足您所需要的一切?


//C++ Example

#include <iostream>
using namespace std;

int doHello (std::string&);
int main() {
    std::string str1 = "perry";
    cout << "String=" << str1 << endl;
    doHello(str1);
    cout << "String=" << str1 << endl; // prints pieterson
    return 0;
}

int doHello(std::string& str){
    str = "pieterson";
    cout << "String=" << str << endl;
    return 0;
}

In the above case, as expected the string 'str1' reference is modified when str reference is modified

//Java Example

public class hello {

    public static void main(String args[]){
        String str1 = "perry";
        System.out.println("String=" + str1);
        doHello(str1);
        System.out.println("String=" + str1); // does not prints pieterson
    }

    public static void doHello(String str){
        str = "pieterson";
        System.out.println("String = " + str);
    }
}

In Java, String str and String str1 are two different objects initially referencing the same String, so when we change str reference in doHello(), str1 reference does not get changed.

How can we achieve C++ style functionality in Java with Strings, Collections such as List, Vectors, other Objects.

Update:

Thanks Jon for a wonderful explaination, I believe any Java beginner will surely come across this question. Let me explain what problem i ran into while using lists.

//bad doHello() 

void doHello(List inputList) { 
    inputList = getListFromAnyFunction(); // wrong, didnt work 
} 

// good doHello 

void doHello(List inputList) { 
    inputList.addAll(getListFromAnyFunction()); // worked 
}

Thanks Powell and Harshath for your explainations and code samples.

解决方案

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<String> items)
{
    items.add("Hello");
}

You could then call this like so:

List<String> list = new ArrayList<String>();
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<String> withHello(List<String> items)
{
    List<String> newList = new ArrayList<String>(items);
    newList.add("Hello");
    return newList;
}

You'd then call it like this:

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

Does this answer everything you needed?

这篇关于C ++引用和Java引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆