• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can i make a class Immutable if it has an instance variable of java.lang.Object?  RSS feed

 
Amit Cngh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
final public class ImmutableWithObject {

final Object obj;
final List myList;

ImmutableWithObject(Object obj1, List list) {
this.obj = obj1;
this.myList = ((List) ((ArrayList) list).clone());
}

public Object getObj() {
return this.obj;
}

public List getMyList() {
return (List) ((ArrayList<String>) this.myList).clone();
}

public static void main(String[] args) {

ImmutableWithObject io = new ImmutableWithObject(new Date(),
new ArrayList());

((Date) io.getObj()).setDate(22);

System.out.println((Date) io.getObj());
}
}

Result : Mon Aug 22 00:50:04 IST 2011

wich is incorrect.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't do this:

By allowing other classes access to the object, you destroy the immutability of the class.
 
Amit Cngh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then Paul , how can we get the copy of Object?
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aha. So your question is really the old FAQ about how to clone an arbitrary Object. To which the answer is that you can't.
 
Amit Cngh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So , we can't make ImmutableWithObject class immutable ?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't. Any class that exposes non-immutable members cannot be immutable.
 
Amit Cngh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But that i have done with List . Instead of using reference to list we can use can use deep copy.and it will become Immutable.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!