PDA

View Full Version : Possible Java bug?



foodpk
May 16th, 2007, 05:01 PM
Holy crap, this is a strange one. I can't believe this is happening. I'm working on a class assignment, which is making a class in Java that behaves as a mathematical set and to implement methods for adding and removing elements to the set and then functions for a union of two sets, intersection and symmetric difference. A set has an array of strings inside it. I've implemented everything except the symmetric difference and while doing the symmetric difference (which is basically union minus the intersection), something strange happens.


Set sa = new Set().add("a").add("b").add("c");
Set sb = new Set().add("c").add("d").add("e");
sa.printAll(); //this outputs: a b c
sb.printAll(); // this outputs: c d e
//all is well so far
Set union = Set.union(sa, sb); //i make a new set which is the union of two
Set intersection = Set.intersection(sa,sb); //a new set which is the intersection
sa.printAll(); // this outputs correctly: a b c
sb.printAll(); // now check this out, this outputs: c d e a b

How is that even possible? I didn't even touch sa and sb, I just used them as parameters in a method. And up until now I was 1000% sure that you can't change variables just by passing them as parameters (like you can in C if you pass them by reference). Now this is really, really, freaking strange. Does anyone know what's going on?
I can upload the whole code somewhere if anyone wants.
Also, if I comment out the line with the union, everything behaves as expected. I mean really WTF

foodpk
May 16th, 2007, 06:12 PM
Gah, nevermind, I figured it out. Objects are passed by reference to methods, so you have to create a new instance of such object and manually copy all its fields.
I wish there was a way to just dereference an object when passing it.

Jeff Wheeler
May 16th, 2007, 06:14 PM
If you have to create a new object exactly the same as the original, my guess is you're doing something wrong. :-/

Do you want it to be a mutable object?

foodpk
May 16th, 2007, 06:23 PM
Nah, what I'm doing is I have an object called Set which has an array of strings. It's like a mathematical set. I have a static function called union(a, b) which returns the union of sets a and b.
I have to create copies of a and b, then determine which one is longer and then add all the elements of the shorter one to the longer (provided they're not in already). If I don't create copies, it actually modifies the object you passed in the parameter.

BradLee
May 16th, 2007, 07:32 PM
Just for reference, in Java objects are ALWAYS passed by reference, and primitives (int, etc...) are ALWAYS pass by value.

This kind of stuff can really screw you up if you aren't aware of it.

foodpk
May 16th, 2007, 07:57 PM
Yeah, haha, wish someone told me that before I spent 1 hour debugging such a trivial thing.
Also, arrays are passed by value.