【发布时间】:2010-11-02 01:30:59
【问题描述】:
//C++ 示例
#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;
}
在上述情况下,正如预期的那样,当 str 引用被修改时,字符串 'str1' 引用被修改
//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); // does not prints pieterson
}
public static void doHello(String str){
str = "pieterson";
System.out.println("String = " + str);
}
}
在 Java 中,String str 和 String str1 是两个不同的对象,最初引用同一个 String,所以当我们在 doHello() 中更改 str 引用时,str1 的引用不会改变。
我们如何在 Java 中使用字符串、List、Vector 等集合、其他对象来实现 C++ 风格的功能。
更新:
感谢 Jon 的精彩解释,我相信任何 Java 初学者都会遇到这个问题。 让我解释一下我在使用列表时遇到了什么问题。
//bad doHello()
void doHello(List inputList) {
inputList = getListFromAnyFunction(); // wrong, didnt work
}
// good doHello
void doHello(List inputList) {
inputList.addAll(getListFromAnyFunction()); // worked
}
感谢 Powell 和 Harshath 的解释和代码示例。
【问题讨论】: