Object.equals() question.

Lets say i have a class:
public class MyClass{
int x;
int y;
int z;
}And i have two objects: one and two...
will
one.equals(two)return true if the fields for both objects hold the same values?
or return true if they both point to the exact same object?
Edited by: JamesBarnes on Oct 8, 2008 12:34 PM

hmm ok, how about this:
i went to add my own equals method to my class:
public class Block{
private int x;
public boolean equals(Block block){
if this.x == block.getX(); // <-- Problem
public int getX(){
return x;
}You can probably see what is going on here, i want to pas the equals method an object of type Block, but because the equals method is within Block it would seem that the method block.getX() cannot be used.
Bizzarrely (im using net beans) although the fields are all private access i can see the fields of the passed "Block block" but not the methods that belong to block.
I can sort of see the problem, calling accessor methods from within a block, its sort of like delving into it's self, but i cant see how else to check for similar objects.
I hope i have made the problem clear,
J

Similar Messages

  • Question about "java.lang.Object.equals()".

    public class TestEquals {
      private int a;
      private int b;
      public TestEquals(int a,int b) {
        setA(a);
        setB(b);
      public int getA() {
        return a;
      public void setA(int a) {
        this.a = a;
      public int getB() {
        return b;
      public void setB(int b) {
        this.b = b;
      public static void main(String[] args) {
        TestEquals te01 = new TestEquals(1,2);
        TestEquals te02 = new TestEquals(1,2);
        System.out.println("te01 equals to te02: " + te01.equals(te02));
        te01.setA(2);
        System.out.println("te01 equals to te02: " + te01.equals(te02));
    }The result is:
    te01 equals to te02: false
    te01 equals to te02: false
    Why the first case is false?

    You didn't override Object.equals() in your TestEquals class. So, you are calling Object.equals(), which just compares reference values. You need to write your own equals() method (presumably, make sure te01.a==te02.a and te01.b==te02.b). Depending on what you do with your objects, you would want to override Object.hashCode(), too.

  • Does making objects equal null help the gc handle memory leakage problems

    hi all,
    does making objects equal null help the gc handle memory leakage problems ?
    does that help out the gc to collect unwanted objects ??
    and how can I free memory avoid memory leakage problems on devices ??
    best regards,
    Message was edited by:
    happy_life

    Comments inlined:
    does making objects equal null help the gc handle
    memory leakage problems ?To an extent yes. During the mark phase it will be easier for the GC to identify the nullified objects on the heap while doing reference analysis.
    does that help out the gc to collect unwanted objects
    ??Same answer as earlier, Eventhough you nullify the object you cannot eliminate the reference analysis phase of GC which definitelely would take some time.
    and how can I free memory avoid memory leakage
    problems on devices ??There is nothing like soft/weak reference stuffs that you get in J2SE as far as J2ME is concerned with. Also, user is not allowed to control GC behavior. Even if you use System.gc() call you are never sure when it would trigger the GC thread. Kindly as far as possible do not create new object instances or try to reuse the instantiated objects.
    ~Mohan

  • Difference between Object equals() method and ==

    Hi,
    Any one help me to clarify my confusion.
    stud s=new stud();
    stud s1=new stud();
    System.out.println("Equals======>"+s.equals(s1));
    System.out.println("== --------->"+(s==s1));
    Result:
    Equals ======> false
    == ------------> false
    Can you please explain what is the difference between equals method in Object class and == operator.
    In which situation we use Object equals() method and == operator.
    Regards,
    Saravanan.K

    corlettk wrote:
    I'm not sure, but I suspect that the later Java compilers might actually generate the same byte code for both versions, i.e. I suspect the compiler has gotten smart enough to devine that && other!=null is a no-op and ignore it... Please could could someone who understands bytecode confirm or repudiate my guess?Don't need deep understanding of bytecode
    Without !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    25
       7:   aload_1
       8:   checkcast       #2; //class SomeClass
       11:  getfield        #3; //Field field:Ljava/lang/Object;
       14:  aload_0
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  if_acmpne       25
       21:  iconst_1
       22:  goto    26
       25:  iconst_0
       26:  ireturn
      LineNumberTable:
       line 6: 0
    }With !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    29
       7:   aload_1
       8:   ifnull  29
       11:  aload_1
       12:  checkcast       #2; //class SomeClass
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  aload_0
       19:  getfield        #3; //Field field:Ljava/lang/Object;
       22:  if_acmpne       29
       25:  iconst_1
       26:  goto    30
       29:  iconst_0
       30:  ireturn
      LineNumberTable:
       line 6: 0
    }

  • Docs about RowSet, and Object RowSet questions?

    Docs about RowSet, and Object RowSet questions?
    I can find RowSet forum, so I ask here!
    Can you give me URLs where I can find more about RowSet and URLs for any RowSet implementation?
    Does Borlans, Oracle, IBM, etc., have RowSet implementation?
    I find out about Sun's RowSet implementation, but I can't find Object Rowset in this implementation?
    Is it possible to develop Object RowSet and is it useful?
    I know about O/R tools like Hibernate, but Object RowSet can be useful?
    Run SQL query and get Objects, or maybe even run Object query (like EJB or Hibernate or JDO have) and get Objects.
    No XML mapping mess and simmilar, like with EJB or Hibernate or JDO?

    You can try
    http://java.sun.com/developer/Books/JDBCTutorial/chapter5.html
    This is a tutorail for RowSet

  • Nested object equality - design pattern

    Looking to solve a problem in my own code, I wanted to see if and how the problem is solved in the java library.
    I would have liked this code to output "true", to see how it's done.
    Set set1 = new HashSet();
    set1.add("a value");
    set1.add(set1);
    Set set2 = new HashSet();
    set2.add("a value");
    set2.add(set2);
    System.out.println(set1.equals(set2));Well the code ends with a StackOverflowError on hashCode(). Just using a Set which implements hashCode to return a constant value would shift the problem to the equals-method.
    I think one possible solution would be to implement the hashCode method to set a instance variable (computingHash = true) while hashcodes of fields are computed. If the variable is set when hashcode is invoke a RecursiveHashRuntimeException is thrown which is is caught by the invoking hashcode method which would then return a constant value or ignore the corresponding field for hash-computation.
    Similarly the equals method would add the obj (passed to equals) to a set (instance variable) named assumeEqualTo, if the obj is in assumeEqualTo when the method is invoked it returns true. The value is removed from assumeEqualTo before the method that added it returns.
    This approach would require the equals and hashcode methods to be - at least partially - synchronized (if multithreading is an issue), an alternative would be to use ThreadLocal variables to detect and handle recursive invocations.
    I'm not sure how the two approaches compare in terms of performance, and I would welcome any other approach to solve the problem. Note that the class being compared should not be required to know details about the contained classes and the nesting may also be indirect as in:
    Set set1 = new HashSet();
    Set set2 = new HashSet();
    set1.add("a value");
    set1.add(set2);
    set2.add("a value");
    set2.add(set1);
    System.out.println(set1.equals(set2));Also it would be nice if the impact on performance could be kept minimal for all instance that happens not to be self-containg.
    cheers,
    reto

    should be slightly different as for sets the orderis
    irrelevant
    I don't follow. You would presumably only return
    true as a whole if every element in the Set also
    returned true. So, yes, order is irrelevant. just wanted to say that you must return true iff you find a mapping from set1 to set2 where all elements are equals
    No, I mean that if you add a Set to itself, and then
    iterate over it, you will implicitly be performing
    recursion, leading to a StackOverflowError
    eventually. That is why you need to store a
    collection (or array) with all the objects already
    analyzed. What do you mean by "already analyzed"? I mean how would you prevent recursion with this?
    You need to compare what is being
    currently being inspected along with checking what
    you already processed for object equality (==) so you
    do not get the stack overflow.I don't get it, in
    Set set1 = new HashSet();
    Set set2 = new HashSet();
    set1.add(set2);
    set2.add(set1);
    set1.equals(set2);The equals method returns true iff set2.equals(set1), which would - in the algorithm I proposed - return set1.add(set2) which is true as set2 is contained in the Set assumeEqualTo. I interpreted the contract specified by java.util.Set to return true on equals for indistinguishable object - not sure if this is correct for mutually referencing sets, but pretty convinced for non-refrencing self containing sets, as in my first example or for all sets returned by:
    createSet() {
      Set s1 = new HashSet();
      Set s2 = new HashSet();
      s2.add(s1);
      s1.add(s2);
    }Imho, it would break be against the specification in java.util.Set to return false on createSet().equals(createSet()).
    reto

  • String Object equals method question

    What is the difference between these two lines of code:
         boolean ok = myString.equals(�foo�);
         boolean ok = �foo�.equals(myString);

    If myString is null, the first one will throw a NullPointerException, whereas the second one will just evaluate to false.
    If you know myString won't be null, I find the first one more natural looking, but that may just be personal preference.
    If there's a chance that myString could be null, and it's valid for it to be null and you just want to handle that like any other unequal case, then the second one saves you an explicit null test, since String's equals method does it ayway.
    String str = null;
    str.equals("foo"); // #1
    "foo".equals(str); // #2 Do you understand why #1 throws NullPointer exception and why #2 does not?

  • Why is the Integer wrapper class object and primitive object equal ?

    This is my code :
    package obectorientation;
    public class oo3 {
         public static void main(String[] args) {
              int x=1; float y=1.0F;
              int x1=1;
                                    Integer y1= new Integer(1);
              if(x1==y1)
                   System.out.println("Equal");
              else
                   System.out.println("NOT Equal");
    O/P : EqualMy question is why are x1 and y1 equal ? Won't y1 be a different object and x1 just a primitive variable ?
    Thanks in Advance.

    Specifically, it's because y1 gets unboxed before the comparison. What's really happening is effectively: if ( x1 == y1.intValue() )

  • System and Object privileges question

    hello everyone.
    I was really making it a priority to really understand both system and object privileges for users. I have setup a couple of 'sandboxes' at home and have done lots of testing. So far, it has gone very well in helping me understand all the security involved with Oralce (which, IMHO, is flat out awesome!).
    Anyway, a couple of quick questions.
    As a normal user, what view can I use to see what permissions I have in general? what about permissions on other schemas?
    I know I can do a:
    select * from session_privs
    which lists my session privileges.
    What other views (are they views/data dictionary?) that I can use to see what I have? Since this is a normal user, they don't have access to any of the DBA_ views.
    I'll start here for now, but being able to see everything this user has, would be fantastic.
    Cheers,
    TCG

    Sorry. should have elaborated more.
    In SQLPLUS, (logged in while logged into my Linux OS), I am working to try and get sqlplus to display the results of my query so it is easy to read. Right now, it just displays using the first 1/4 or 1/3 of the monitor screen to the left. Make sense? So it does not stretch the results out to utilize the full screen. it is hard to break down and read the results because they are "stacked" on top of each other.
    Would be nice if I could adjust sqlplus so the results are easier to read.
    HTH.
    Jason

  • Object oriented question

    I am sure my n00bieness is going to shine here but I have a pressing question.
    I have two classes that do a similar activity they attach some elements to an xml document and then call a web service.
    Object A uses in its method signature different object parameters then Object B does.
    For example -
    Object A{
      public ProprietaryObject doMagic(ProprietaryObject po){
        //do stuff
    Object B{
      public DiffProprietaryObject doMagic(DiffProprietaryObject po){
        //do stuff
    }There is more than one method that is similar between the two objects but this is just to get the point across.
    Anyway, Instead of creating two separate objects that do "almost" the same thing (on different object types) how can I create an elegant solution to this?
    The problem I run into is that if I create a common interface for these two object to implement the object use different proprietary objects to do their work.
    I find that I keep using the instanceof operator everywehre to determine the object type.
    Hope this is not explained to horribly...
    Any help is appreciated!

    I'd create an Interface which defines a common access method for the-operations-you-require from both proprietory classes, then implement that interface in a couple of "boundary" classes which "wrap" the proprietory classes...
    If possible, extend the disparate proprietory classes, and delegate to the appropriate methods of the "real" classes.
    If the propritory classes are final then you have to write a ship load more "boilerplate" code... every single fraggin method has to pass the buck to the appropriate method of the private instance of the "wrapped" class, and return the result... which isn't usually too bad once you roll up your sleeves and get into it.
    From memory (mine is poor) this is the essence of the [Adapter pattern|http://en.wikipedia.org/wiki/Adapter_pattern].
    Like a said, there may be quit a bit of work involved, but the advantages usually outweigh the costs... You can "refer to" the disparate proprietory classes seemlessly throughout the rest of your system... if ProprietoryClassA changes (in the next release) you can (hopefully) adapt your adapter to those changes, without having to modify all your consumer code... because it still exposes the same interface... which is the motivation for any boundary class ("Trust no one";-)
    Cheers. Keith.
    Edited by: corlettk on 8/08/2008 06:28 - Better.

  • Should I use Embed or Object - quick question...

    Hi all,
    I've got a few .swf files on my site. One of them uses the following code:
    <object style="float:left;" id="intro" name="intro"
    type="application/x-shockwave-flash"
    data="<?php echo $siteurl; ?>/intro_movie/intro.swf" width="300"
    height="188">
    <param name="wmode" value="image" />
    <param name="movie" value="<?php echo $siteurl; ?>/intro_movie/intro.swf" />
    </object>
    Another one uses the following:
    <script type="text/javascript">
    var flashvars = {};
    var params = {};
    var attributes = {};
    swfobject.embedSWF("<?php echo $siteurl;  ?>/swf/testimonials.swf", "_testimonials", "405", "43", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
    </script>
    <div id="_testimonials">
    <a href="http://www.adobe.com/go/getflashplayer" title="Get flashplayer">
    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" width="112" height="33" alt="Get Flashplayer" border="0" />
    </a>
    </div>
    On a computer recently the first example showed up fine but the second example didn't show up at all.
    I just wondered what the correct way to show .swf files is on a webpage.
    I'm very sorry if this is a stupid question but any help you could give me on this would be much appreciated.
    Many thanks
    John Thornley ;-)

    kglad.com
    Thank you for your reply.
    I should clarify that both of those examples are working on my machine. However, on another machine only the top example showed up at the bottom example caused 404 errors as it was trying to load expressInstall.swf which wasn't in the directory.
    This confused me as I wondered if there was any detriment to just having all my swf on my site integrated using the top method?
    I didn't write the bottom example and I don't really understand it fully. I'm not sure whether my best move is to just convert everything to the top example or whether I should try and find a copy of "expressInstall.swf" and try and get the bottom example working on this other machine?
    Which is the correct way?
    Thanks again for your continued support
    Cheers
    John ;-)

  • Help In ABAP Object Certification Question

    Hi ABAP Gurus,
       iam going to write certification Exam on Nov 11. i have got some model question from SAP domain for all the topics Except ABAP Objects which is so important...
    Please anybody send me some Example question you guys got from the Certification Exam
    it will be be grateful to me...
    Thanks a lot in advance.
    Prabhu
    SAP Lead Consultant

    Hi,
    Sending ABAP Objects questions is not an option but normally, your concepts are tested for:
    - Classes and objects
    - Inheritance
    - Casting
    - Interfaces
    - Events
    - Global classes and interfaces
    - Exception handling
    - Dynamic programming
    You can use help.sap.com to take a look at these topics one by one. Hope this helps.
    Good luck.

  • LR2:DNG - PSCS3:'Smart Object' workflow question

    Hello, I've just started working with DNG files exported as Smart Object from LR2 to PSCS3 and I would appreciate some feedback on my experiences thus far.
    Let us assume that I've made basic corrections to _DSC1190.dng within LR2. I then want to apply a filter to a particular region of the DNG file with all of my LR2 adjustments applied.
    1. Here are the steps I currently follow:
    1.1. Right-click on the DNG file and select 'Edit In'->'Open as Smart Object in Photoshop...'. This results (I believe) in the DNG file with all of my LR2 changes being embedded within a smart object and the resulting temporary file being opened within PSCS3.
    1.2. I perform my edits in PSCS3 and save the file as a PSD (i.e. _DSC1190.psd). As long as I was smart about things, I can now go back at any time and alter any of the changes I made in PSCS3, as well as access the DNG file within the smart object to make and ACR changes I desire.
    1.3. If I want the new PSD file to be added to my LR2 catalog, I then need to navigate to where it was saved and manually add it.
    1.4. If I want to make any exposure adjustments, or really, any adjustments that I'd normally make within LR2 or ACR to _DSC1190.psd, I need to open the file within PSCS3, double click on the smart object to get the ACR dialog, make my changes, and voila!, the PSD composite now reflects those changes.
    1.5. If I make any changes within LR2 to the original DNG file (i.e. _DSC1190.dng), those changes are *not* reflected within the PSD file.
    1.6. Questions
    1.6.1. Is what I've described the expected behavior?
    1.6.2. Although it might seem silly to some, and may present a technical challenge not worth the trouble, it seems it would be beneficial to have the smart object exported from within LR2 to PSCS3, contain a link to the original DNG file, and not now have two separate DNG files, one visible to the file system, and the other embedded within the smart object saved as presumably a PSD. I'm sure there are a lot of corner cases to consider, but it just seems very strange to now have two files wherein if you want to change something you would normally do through LR2 or ACR, you now have to do it in two different programs to two different files. Is this a problem Adobe has considered, i.e. any discussion about supporting this perhaps in an update to LR2 along with PSCS3/4?
    Thanks much for any help/insight,
    Matt

    I haven't tried doing what you are in CS but do you have the embed xmp into file enabled or are you updating the xmp by saving it out of LR CTRL-s? Do you have ACR set to read the xmp data? I don't have access to LR at the moment but will have a play l8r and get back to you if no one else does.

  • Business Object Modeler Question

    Hi Experts,
    I'm new to CE and currently trying to figure out what can I do with it?
    Assume that I'm planning to create an application to follow activities that our consultants doing.
    For this, we're planning to use Local Portal Database to store datas.
    When I checked, "Business Object Modeler" is a tool which helps to create business objects and generates tables behind and access services automatically.
    Then generating a Web Service for this BO and then using the WS with VC and WD4J is a great asset for us.
    But, my questions?
    1. Is this a right approach for  such scenario?
    2. I've created a sample BO and generated WS and tried to use with VC. Create, Delete, Reand and Update Operations can be made available for WebService, but I'm unable to add FindAll or FindByMultiple Parameter operations to Web Service?
    Any idea for Q1 and answer for Q2 will be appreciated.
    Regards

    Hi,
    Yes, You have to arite the code.Actually, Application services are the place where you will wrtie your business logic.
    In th application service operations you have to call the business object operations.
    For architechturel guidelines you can go [through thii doc|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/00caf8bd-487a-2a10-36a9-93d840309310].
    answer to second question:
    You can't change the code in the BO operations. What ever you want, you have to do it in the application servcies only.
    Create an application service operation  say:
    operation(). Create a input/output data structures.
    Exapmle:     OperationResponce operation(OperationRequest).
    Yuor lists add to the  OperationRequest datatype. Similarly for  OperationResponce also. In this case you don,t have any issues.Actually this is the standered for Web Services.
    [This document|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/f0d97ec6-5de0-2a10-a5b3-b5926075566c], you can use as an example
    [CE 7.1 Tuorial Center.|https://www.sdn.sap.com/irj/sdn/nw-development?rid=/webcontent/uuid/903c2cdb-98d6-2a10-84b7-ab22535de11a]
    Reward Points, If you feel it is useful.
    Sampath

  • 9 shared objects performance question

    I have 9 shared objects 8 of which contain dynamic data which i cannot really consolidate into a single shared object because the shared object often has to be cleared.....my question is what performance issues will I exsperience with this number of shared objects .....I maybe wrong in thinking that 9 shared objects is alot.....anybody with any exsperience using multiple shared objects plz respond.

    I've used many more than 9 SO's in an application without issue. I suppose what it really comes down to is how many clients are connected to those SO's and how often each one is being updated.

Maybe you are looking for