Posts Tagged arraylist

Private Fields of Reference Type

Hi, today I stumbled upon a strange problem while wriring some java code.
There is a class with a private field of reference type, say an ArrayList. Now,what is the use of private fields? They are used so that they can not be modified from outside the class like public fields. General practice is to provide getter methods in the class to return the values of private fields.It goes fine with the primitive type variables and Strings(because Strings are immutable). But when the field is of reference type, we can still change its value.Have a look at the code:

import java.util.*;

class Aclass
{

private ArrayList list;
private String s= "My string";

public Aclass()
{
list= new ArrayList();
list.add("Hello");
}

public ArrayList getList()
{
return list;
}

public String getString()
{
return s;
}
}

public class TestPrivate
{

public static void main(String args[])
{
Aclass ob= new a();
ArrayList alist= ob.getList();
System.out.println(l2);
alist.add("Hi");
ArrayList anotherList= ob.getList();
System.out.println(anotherList);

String s2= ob.getString();
System.out.println(s2);
s2="changed";
String s3= ob.getString();
System.out.println(s3);
}
}

When you run this code,the output is:
[Hello]
[Hello, Hi]
My string
My string

You can see that content of list has been changed, but for string, they are not changed.So you can change the list object even if it is private.It is because the getList() method returns the reference to the same list object, so we can modify the list even if it is private.Now if you think that it is some loophole or bug of java,the you are wrong.It is just a simple basic concept of reference type variables.

Now, what should you do to avoid this thing. You have to modify the getList() method so that it returns the clone of list, not the actual list object.Here is the solution:

public ArrayList getList()
{
return (ArrayList) list.clone();
}

clone() will return the clone of object, not the actual list. Return type of clone() is Object, so we have to typecast it to ArrayList. Any modification done from the reference returned by this method will not change the actual one.For more information on clone() method,
go here.

Advertisements

, ,

1 Comment