when will a function change the param?

import java.util.*;

publicclass test

{publicvoid setDate(Date d)throws Exception

{

Thread.sleep(1000);

d=new Date();}

publicvoid add(HashSet h)

{

h.add("1"+Math.random());

}

publicstaticvoid main(String[] args)throws Exception

{

test t=new test();

Date d=new Date();

HashSet h=new HashSet();

System.out.println(d.getTime());

System.out.println(h.size());

t.setDate(d);

t.add(h);

System.out.println(d.getTime());

System.out.println(h.size());

}

}

=================

result:

1127460274718

0

1127460274718

1

=============

the first function,with a Date param after execute, the param doesn't change.

the second function,with a HashSet param, after execute the param has changed,

is it means the function only can modify the param's inner element,

but can not new one element to param.

[1753 byte] By [dinghaijianga] at [2007-10-2 0:37:50]
# 1

You are reffering to the pass by reference. COmplex type within the box are more of a pointer like pass. Basis typs like String, Date, etc... not. Modification to those are local to the funtion or class. The hash return a reference and so the date is modified. The first Date not. It's something to remember. When you start programming ejb's it will be even more complex because then you also have local and remote interface.

Marteijn

Maerteijna at 2007-7-15 16:52:29 > top of Java-index,Administration Tools,Sun Connection...
# 2
but when the function is like this:public void test(Date d){d.setYear(1000);}then you will found it modified.so I think you can not reference a param to a new reference, but can modify it.
dinghaijianga at 2007-7-15 16:52:29 > top of Java-index,Administration Tools,Sun Connection...
# 3

> but when the function is like this:

> public void test(Date d)

> {

> d.setYear(1000);

> }

> then you will found it modified.

> so I think you can not reference a param to a new

> reference, but can modify it.

That is correct, as is specified in pass by reference.

You cannot change the reference, but you can change the data that reference refers to.

So you cannot replace the date by another date, but you can change the value of the date you do have to something else.

jwentinga at 2007-7-15 16:52:29 > top of Java-index,Administration Tools,Sun Connection...