11 February 2011

And at last I know why some Objects should be mutable!

Hello Everybody ....

We all know the difference between mutable and immutable objects as we know the difference between StringBuffer and String objects.

But believe me, it is the first time to know that this difference is very very vital in some situations.

Let me tell you a story ....

I am a some Servlet Filter that I need to modify some Http headers in it before sending the request to the Servlet to process the request.

I looked at the HttpServletRequest methods trying to find a method allows me from modifing the request headers (some thing like request.setHeader("")) but i cannot.

I tried to make a trick (this is the point) on the same way of:

// suppose we have employee object that composes a manage object but with no setter method..
// we need to change some data in the employee's manager we could do:

Employee e = ....;
e.getManager().setManagerName("new name");

I tried to do the following:

String headerValue = request.getHeader("headerName")
headerValue.set("newValue");/// ooooops, Strings are mutables!!!

For such case, The string object is mutable....
Post a Comment