English 中文(简体)
为什么某些 j子能够获取价值参考[复制]。
原标题:why do some java objects can t get value references [duplicate]
  • 时间:2012-05-13 07:04:51
  •  标签:
  • java
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Is Java pass by reference?

when I used some java class like (Integer, File, Boolean) if I pass the instance as an argument to a function and try to change its value after I use this value outside function, the value remains unchanged.

例如:

private void run(){
        File tmpFile;
        setFile(tmpFile);
        System.out.println(tmpFile.getAbsolutePath());  //error tmpFile is null
    }

private void setFile(File xFile){
    xFile = jFileChooser.getSelectedFile();  // this returned object file
}
最佳回答

The short answer is that Java uses call-by-value, not call-by-reference.

在您的<代码>File方法中,您被指派到x。 文件只改动了当地变量。 它不改动<代码>tmpFile在<代码>run(方法中的位置。

您应撰写该守则,以便setFile回归数值;例如:

    private void run(){
        File tmpFile = getFile();
        System.out.println(tmpFile.getAbsolutePath());
    }

    private File getFile() {
        return jFileChooser.getSelectedFile();
    }

(说明:我改变了方法名称,因为一种名为<代码>的方法。) iii 确实没有做任何事情,令人极为怀疑。

问题回答

Java always passes by value. You shouldn t expect any other behaviour.

A method can only change an object when you pass a reference (The reference is still passed by value)





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签