Wednesday, April 09, 2008

Java Object References

Someone was writing a parser and while unit testing he got bugged because the two lists that he was creating using the same objects was getting modified without he explicitly doing so. After having a look at the code it turned out to be a simple problem. In java, you deal with object references as against objects. So if you have

Object o1 = new Object(); Object o2 = o1; Object o3 = o1; You have a single object but 3 references. //heres a snippet of what my colleague was actually trying to do. He complained that list1 and list2 were getting modified on their own…Really??? Have a look

import java.util.ArrayList; class Emp { private int code; public Emp(int c) { code = c; } public void setCode(int c) { code = c; } public String toString() { return ""+code; }

} public class References { public static void main(String[] args) { ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); Emp e1 = new Emp(100); Emp e2 = new Emp(200); Emp e3 = new Emp(300); list1.add(e1); list1.add(e2); list1.add(e3); list2.add(e1); list2.add(e2); list2.add(e3); System.out.println(list1); System.out.println(list2); e2.setCode(900); System.out.println("--------"); System.out.println(list1);; System.out.println(list2); } }

p.s. Sorry about teh formatting....this stupid doesnt maintain the format that i write in and i am too lazy to use html tags and google docs is not working....so just pick the snippet and paste in a decent browser. it will work ;)