> what will be the result when we compare 2 objects
> with the .equlas() method and == operator
talking to yourself? or asking us to answer for you?
if the .equals method has NOT been overridden by the object you are invoking it on, then .equals() and == will return the same results. Those results are that if the two objects are in fact only one object being referenced by (possibly) two different variable references.
if the .equals method HAS bet overridden by the object you are invoking it on, then it will perform in whatever way that class instructs it to perform. The == method, however, will perform just as it did before.
- Adam
> hw to create a immutable object
>
Joshua Bloch talks a little about creating immutable objects in Effective Java. It's a great book, and I really recommend it to any java programmer.
Anyway, to create an immutable object, you need to make sure that you encapsulate all of you objects data (i.e. make all fields private). Then make sure that you do not provide any public methods that allow the user to modify the value of those fields.
Also, ensure that you do none of your private methods could have side effects that modify those fields. As a general rule, you should make those fields final if possible to prevent them from being modified.
Also, any get methods for objects should actually return a copy of those objects, since allowing a client to get the actual object would allow them to modify the data stored by that object, and you class would no longer be immutable.
And finally, you should really declare your class final, because if it can be extended, then a subclass of it might not be immutable.
There are probably more things you should think about too, but really, it depends on the class. The main thing is to think about the ways in which an object could potentially be modified, and prevent them.
- Adam
> hi
> thanks for ur wonder full information
>
> can u tell me , in which kind of situations we may
> create a Immutable class
I suppose you COULD use immutable objects in many situations. One that comes to mind immediately is when you decide to use the fly-wieght pattern.
For example, consider string literals in java. When you create a string literal (that is, you create a string by simply enclosing it in quotations marks " " without calling the new String constructor) the jvm actually makes a pool of those strings. Any two identical string lilterals will actually refer to exactly the same object. You can also use the String.intern() method to obtain a String from that pool of strings. Now, consider what would happen if String WAS mutable:
String string1 = "Hello World";
String string2 = "Hello World";
string1.replace('e', 'a');
System.out.println(string2);
if String was mutable, then printing string2 (and any other reference to the same interned string) would see the effects of the change made to String1. In many cases, this would be what is wanted, but in cases such as this, where pooling is not necessarily an explicit requirement of the designer, this might be a bad thing.
Another place where immutable objects have been used for a Fly Wieght pattern in the JFC is in SWING borders. For many borders, javax.swing.BorderFactory has been written to maintain a pool of borders that it has created, and return a reference to an already existing border matching the requirements, if such a border has already been created. If a line border was mutable, consider what would happen if I did this:
panel1.setBorder( BorderFactory.createLineBorder( Color.black ) );
panel2.setBorder( BorderFactory.createLineBorder( Color.black ) );
panel3.setBorder( BorderFactory.createLineBorder( Color.black ) );
panel4.setBorder( BorderFactory.createLineBorder( Color.black ) );
now, lets say that at some point I wanted to highlight panel1 by making it's border red.
panel1.getBorder().setColor( Color.red );
since all of the panels have a reference to exactly the same border, the effect would be that they would all turn red. Hence, the Line border is immutable, and I would have to use the following code instead:
panel1.setBorder( BorderFactory.createLineBorder( Color.red ) );
A third place where such caching is done is Integer.valueOf( String ). The same can be said about any other class that extends from java.lang.Number
That's one really good reason for Immutable Objects.
Another good reason is for thread safety. Consider a mutable object, such as, oh, say, StringBuffer. If I knew that I was going to be using StringBuffer from two different threads, I would need to synchronize all of it's mutators (those are the methods that allow the value to change). I would ALSO need to synchronize all of the accessor methods, because if I didn't, I could potentially try to read the value of the StringBuffer when it was in an intermediate / corrupt state that would be completely non-sensical.
On the other hand, IF I use String, I have no need to synchronize the accessors, because there ARE no mutators, so it is completely impossible that the string woudl be in an intermediate / corrupt state when I attempted to read it, because no other thread could possible be attempting to modify it. This is another advantage of Immutable objects.
Another good reason is that immutable objects are safe in the presence of malicious code, or in the presences of sloppy, poorly behaved code, because they cannot be changed, therefore they cannot be changed in innappropriate ways or at innappropriate times. This makes them excellent keys for maps, as well, becauase once they are set as the key, that key is guaranteed not to change.
There are also other excellent reasons listed in the following article (as well as most of the reasons I have mentioned here):
http://www-128.ibm.com/developerworks/java/library/j-jtp02183.html
This is an excellent article, and also describes how one might go about creating an immutable object class.
Hope this helps!
- Adam
> hw to create a immutable object
>
> like String -- String is a immutable object
>
> StringBuffer it is a Mutable Object
Search this question in the forum.
--Maybe you should try to prevent your methods from causing some changes in your class instances.
--Maybe, by creating a class whose members can only show somethings about the class instead of making changes on it.
> > hw to create a immutable object
> >
> > like String -- String is a immutable object
> >
> > StringBuffer it is a Mutable Object
>
> Search this question in the forum.
>
> --Maybe you should try to prevent your methods from
> causing some changes in your class instances.
yes, this is correct. depending on how complicated the class is, however, this is easier said than done. One decent method of doing this is to make all fields final. That way, the compiler will tell you if you try to change them. This, of course, doesn't prevent you from calling mutators on those fields, if those fields are themselves mutable objects. It's often worthwhile, then, to use fields that are also immutable objects.
> --Maybe, by creating a class whose members can only
> show somethings about the class instead of making
> changes on it.
yes, but more than this, it's important that you don't allow clients to call mutators on objects that may be returned from accessors. There are two ways to do this:
1. Make sure that any object returned by an accessor is an immutable object; or
2. Return a copy of those fields, rather than the exact reference to those fields.
- Adam
Its my understanding that if you want to truely compare objects for equallity, you should oversride the .equals() and the .hashCode() methods.
Pleas correct me if I'm wrong.
I believe the .equals() compares the objects state (if coded that way), but there may in fact be two different objects.
JJ
> Its my understanding that if you want to truely
> compare objects for equallity, you should oversride
> the .equals() and the .hashCode() methods.
>
> Pleas correct me if I'm wrong.
>
> I believe the .equals() compares the objects state
> (if coded that way), but there may in fact be two
> different objects.
>
> JJ
that is correct-ish...
TECHNICALLY, the .equals method and the .hashCode methods do what ever you want them to do. However, there are specifications for how the SHOULD work, and when a programmer writes code that will CALL those methods, he/she EXPECTS that they will work the way Sun has indicated that they SHOULD. Hence, if they do not, then his/her code will not work correctly either.
A major example is in the Collections framework, in sets and hashmaps, etc. They make use of both hashCode and Equals. For these datastructures to work correctly, if you want two objects to be considered the same, then .equals must return true, and both must return the same hashCode.
The basic contract for hashCode says that if two objects return true under the operation .equals, then they should also return the same hashCode:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#hashCode()
The equals method has a contract as well, the specifies reflexivity, symmetricallity and transitivity, etc. At the bottom of that, it also specifies that it is generally necessary to override hashCode too:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)
And because I think Effective Java is one of the best books out there, here is a sampe chapter of Effective Java that describes exactly how to override methods common to all objectcs (such as equals and hashCode, etc)
http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf
He gives an in-depth explanation of how and why to override both equals and hashCode.
- Adam
> hey you doin
> i was working on a program which should accept only
> numeric values (int, float or double) from the user
> and disallow him to enter String or char.
> can u give me a code for this?
> PS: i am not supposed to use the try catch statements.
Sounds like homework to me - you should probably attempt this yourself.
> hey you doin
> i was working on a program which should accept only
> numeric values (int, float or double) from the user
> and disallow him to enter String or char.
> can u give me a code for this?
no.
> PS: i am not supposed to use the try catch statements.
this sounds like homework. therefore, most definitely no: I will not DO your homework for you. However, I don't mind pointing you in the right direction.
Probably the best place to start looking is the scanner:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
The methods you will want to look at are:
#hasNextInt()
#hasNextFloat()
#hasNextDouble()
and
#nextInt()
#nextFloat()
#nextDouble()
the #nextXXX() methods only throw runtime exceptions, which means you don't have to catch them, but they can still be thrown, which will cause your program to crash.
the #hasNextXXX() methods are the ones that will prevent you from needing to use try and catch statements.
I trust that with this info, you are smart enough to figure the rest out from here.
- Adam