I am unable to understand how this works
public void addToRule(Rule r) {
if (!getRuleList().contains(r)) {
getRuleList().addElement(r);
}
}
If I run this code:
obj.addToRule(r);
System.out.println(getRuleList().contains(r));
it prints out true how can this happen?
btw ruleList is a vector member of the main class and is not a static variable(don’t think this matters but sharing anyway).
import java.util.Vector;
public class RuleEngine{
private Vector ruleList = new Vector();
public Vector getRuleList(){
return ruleList;
}
public void addToRule(Rule r){
if(!getRuleList().contains(r))
getRuleList().addElement(r);
}
public static void main(String args[]){
RuleEngine re = new RuleEngine();
Rule r = new Rule("Rule1");
re.addToRule(r);
System.out.println(re.getRuleList().contains(r));
}
}
class Rule{
public String name = "";
public Rule(String nam){
this.name=nam;
}
}
OK people have told me that this works because of the pass by reference in java. I get it. but what can i do to get a copy of that object instead of its reference?
From your comments it looks like you have not completely understood what the difference is between a value and a reference in Java. Basically, objects are always passed around as references in Java.
Consider
The
getList()method will return a reference to thelistobject. It will not return a copy of thelistobject. Doing something likeWill return true since the first time
getList()is called, a referece to the list is returned, on whichadd(s)is invoked. The second timegetList()is called, it returns a reference to the same list, not a copy of it, not a new list – the same reference. Callingcontains(s)will return true since it the same list onto which the objectswas added.Consider this, however.
This will print out “false”. Why?
test1.getList()returns a reference to the list inside test1 andtest2.getList()returns a reference to the list inside test2. Here,swas added to test1:s list, so it will not be contained inside test2:s list.