到目前为止,我见过的所有样本函数都会因某种原因避免返回一个字符串.就Java来说,我是一个新秀,所以我不确定这是否是故意的.我知道在C++中,返回对字符串的引用比返回该字符串的副本更有效.
这在Java中如何工作?
我对Java for Android特别感兴趣,其资源比桌面/服务器环境更有限.
为了帮助这个问题更集中,我提供了一个代码片段,我有兴趣返回(给调用者)字符串页面:
public class TestHttpGet {
private static final String TAG = "TestHttpGet";
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.google.com/"));
HttpResponse response = client.execute(request); // actual HTTP request
// read entire response into a string object
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
Log.v(TAG, page); // instead of System.out.println(page);
}
// a 'finally' clause will always be executed, no matter how the program leaves the try clause
// (whether by falling through the bottom, executing a return, break, or continue, or throwing an exception).
finally {
if (in != null) {
try {
in.close(); // BufferedReader must be closed, also closes underlying HTTP connection
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我可以定义:
public String executeHttpGet() throws Exception {
Run Code Online (Sandbox Code Playgroud)
代替:
public void executeHttpGet() throws Exception {
Run Code Online (Sandbox Code Playgroud)
并返回:
return (page); // Log.v(TAG, page);
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
String是一个引用类型 - 所以当你返回一个字符串时,你真的只是返回一个引用.这很便宜.它不是复制字符串的内容.
| 归档时间: |
|
| 查看次数: |
282 次 |
| 最近记录: |