Clone() and equals()-- puzzled!!   x.equals(x.clone())

hi,
I have an object x that contains only 1 int variable.I clone the object and check for equality with my original object -- I always get false -- why? Something like:
boolean flag = x.equals(x.clone())
Falg is aways false??
Shoudn't the objects be equal?

class
MyClass {
int x,y
public MyClass(int X, int Y) { x=X; y=Y; }
public boolean equals(int X, int Y) { return x==X
=X && y==Y; }
public MyClass clone() { return new MyClass(x,y);
}Well, you'd need to add
public boolean equals(Object obj) {
    return (obj != null)
            && (obj.getClass() == getClass())
            && (((MyClass)obj).equals(x, y));
// and you have to override hashCode. Maybe something like...
public int hashCode() {
    return x ^ y;
}I'd get rid of the equals(int, int) method though and either compare x & y in[b] equals(Object) or have equals(Object) call equals(MyClass) which would then compare the x & y.
Also, clone is always supposed to call super.clone()--it should NOT construct a new object with new. It has to catch CloneNotSupportedException, and return Object.

Similar Messages

  • I just bought a new dell quad core 5i and HAVE DOWNLOADED THE TRIAL VERSION OF PHOTO SHOP - its Slow to open up a small file and equally as slow to print why?

    HELP I just bought a new dell quad core 5i and HAVE DOWNLOADED THE TRIAL VERSION OF PHOTO SHOP - its Slow to open up a small file and equally as slow to print why?

    Use Photoshop menu Help>system Info... use its copy button and paste that info in an append here.
    Supply pertinent information for quicker answers
    The more information you supply about your situation, the better equipped other community members will be to answer. Consider including the following in your question:
    Adobe product and version number
    Operating system and version number
    The full text of any error message(s)
    What you were doing when the problem occurred
    Screenshots of the problem
    Computer hardware, such as CPU; GPU; amount of RAM; etc.

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • Do I need to override enum's hashCode() and equals()?

    Hi all:
    I have a enum type let's say it is
    public enum Type
      ONE,
      TWO;
    }If I want to compare the enum value to see if they are same value or not, let's say I have two:
    Type a = Type.ONE;
    Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
    Can enum Type return the correctly hash code?
    For example the class is like:
    public Class A
      Type type;
      pubilc boolean equals(Object other)
        // here skip check class type, null and class cast
        if(other.type.equals(this.type))
           return true;
        else
         return false;
      public int hashCode()
        int result = 31;
        result += 31 * result + type.hashCode() ;
       // can we get correct hash code from enum here?
        return result;
    }

    Answered by the test code by myself.
    We can use either equals or (==) to see if they are the same value.
    The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • Get item Greater than and equal to today's date...

    Hi,
    We are having issue in getting item greater than today's from SharePoint List. We have a column in list with Date and Time Data type.
    I am using below code to get data greater than and equal to today's date.
    SPQuery query = new SPQuery();query.Query = "<Where><Geq><FieldRef Name='Expires' /><Value Type='DateTime'>"+ DateTime.Today.ToShortDateString() + "</Value></Geq></Where>";
    SPListItemCollection listItemCollection = list.GetItems(query);
    Please suggest what is wrong in above query.
    Regards,
    Amit Chhatbar

    Hi Amit,
    I guess the date is expected to be in UTC and ISO 8601 format. Use the below code and check if it works.
    DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")or DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ")
    Ram Prasad Meenavalli | MCITP | MCTS SharePoint | MCPD SharePoint | http://www.spdeveloper.co.in

  • Difference between == and .equals

    How do they differ in functionality?
    Thanks in advance

    hi javanovice33,
    simply put:
    == tests if two object references point to the same and only one object
    and
    .equals() tests if two object references contain identical contents
    Illustration A:
    String hello1 = "Hello";
    String hello2 = "Hello";
    is hello1==hello2?
    answer: TRUE
    reason: both object references point to the same and only one
    object "Hello". Note that literal String "Hello" is immutable and
    can no longer be changed. JVM memory heap will try to look
    first for the existence of the same value if another object reference
    is initialized to the same literal String "Hello". Therefore, in this case,
    the declaration and initialization above can be rewritten as hello2=hello1.
    is hello1.equals(hello2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Illustration B:
    String hellow1 = new String("Hello");
    String hellow2 = new String("Hello");
    is hellow1==hellow2?
    answer: FALSE
    reason: each object reference points to distinct object in memory
    thus, they are not equal
    Is hellow1.equals(hellow2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Regards,

  • When we override Hashcode and Equal Methods

    Hi....I have doubt regading Hashcode and equal methods
    why we override this two methods....
    why we override hashcode method when we are overriding equal method,
    i would very thankful to give answser
    Thank you
    Ramesh

    hash code is computed to check the equality of two
    objects ,
    that is why if u change the default equal method
    implementation , u need to change the hashcode method
    as well.That's an incomplete answer at best.
    The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
    If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

  • The different between Contain and equals

    I not sure about the different between contain and equals if I want to know if the string have some character or not ?
    thankyou

    HJava wrote:
    Thank you for all the reply,
    I have if (myTYpe.substring(0).contains(""u") ) work
    if if (myTYpe.substring(0).equals(""u") ) not work
    so I post this question, may be I made other mistake
    Thank youIf you wanted to see if the first character of the string was u then it is either
    myTYpe.charAt(0) == 'u'or startWith("u") or matches("^u.*$") etc, etc, etc.
    substring(0) will return the entire String, of course, which you would know if had actually looked at the API docs to find out what it did or even simply printed out the result to see what it did. Seemingly, however, you simply assumed you knew what it did and went on with that false assumption without bothering to even attempt to verify even though it was, already, not producing the results you expected. Instead, you focused on "the difference between contains and equals" which is self-evident in their names and obviously not the problem to begin with.

  • ToString array and equals method

    I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
       public String toString(){
              //should indicate all cities
              System.out.print("Cities :");
              for (int i = 0; i < cities.length -1; i++)
                   return cities;
    Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
       public City getCity(String cityName){
              //returns the City with name cityName (must search for city in the array)
              //if the city does not exist, it returns null
              for(int i = 0; i < cities.length; i++)
                   if(cityName.equals ("cityName"))
                        return ;
                    else return null;
                Message was edited by:
    ehj3000

    great my world class is fixed now im getting missing return statements on the two methods
           public City getCity (String cityName){
          //returns the City with name cityName (must search for city in the array)
          //if the city does not exist, it returns null
             for(int i = 0; i < cities.length; i++)
                if(cities.getName().equals(cityName))
    return cities[i];
    else
    return null;
    public String toString(){
    //should indicate all cities
    System.out.println("Cities: ");
    for (int i = 0; i < cities.length -1; i++)
    return cities[i].getName();

  • One question about Pricing and Conditions puzzle me for a long time!

    One question about Pricing and Conditions puzzle me for a long time.I take one example to explain my question:
    1-First,my sale order use pricing procedure RVAA01.
    2-Next,the pricing procedure RVAA01 have some condition type,such as EK01(Actual Costs),PR00(Price)....,and so on.
    3-Next,the condition type PR00 define the Access Sequences PR00 as it's Access Sequences.
    4-Next,the Access Sequences PR00 have some Condition tables,such as:
         table 118 : "Empties" Prices (Material-Dependent)
         table 5 : Customer/Material
         table 6 : Price List Type/Currency/Material
         table 4 : Material
    5-Next,I need to maintain Condition tables's Records.Such as the table 5(Customer/Material).I guess the sap would supply one screen for me to input the data of table 5.At this screen,the sap would ask me to select one table,such as table 5.When I select the table 5,the sap would go to the screen to let me input the data of table 5.But when I use the T-CODE VK31 or VK32 to maintain Condition tables's Record,I found it's total different from my guess:
    A-First,I can not found one place for me to open the table,such as table 5,to let me input the data?
    B-Second,For example,when I select the VK31->Discounts/Surcharges->By Customer/Material,the sap show the grid view at the right side.At the each line of the grid view,you need to select the Condition Type at the first field.And this make me confused very much.Why the sap need me to select one Condition Type but not the Condition table?To the normal logic,it ought not to select Condition table but not the Condition Type!
    Dear all,I'm a new one in sd.May be this is a very stupid question.But it did puzzle me for a long time.If any one can  explain this question in detail and let me understand the concept,I will appreciate him/her very much.Thank you.

    Hi,
    You said that you are using the T.codes VK31 or VK32.
    These transaction codes are used to enter condition records for standard condition types. As you can see a grid left side having all the standard condition types like price, discounts, taxes, frieghts.
    Pl check using T.code VK11 OR VK12 (change mode)
    Here you can enter the required condition type, in the intial screen. (like PR00, MWST, K004, K005 .....etc)
    After giving the condition type, press enter or click on Combinations icon on top of the screen. Then you can see all the condition tables which you maintained for that condition type. Like as you said table 118, table 5, table 6 and table 4.
    You can select any table and press enter, then you can go into the screen in which you have all the field cataglogues you maintained for that table. For example you selected combination of Customer/Material (table 5) then after you press enter then you can see customer field on top, and material fields.
    You can give all the required values and save the conditon record.
    Hope this is clear.
    REWARD IF HELPFUL.
    Regards,
    praveen

  • I have Photoshop cs5, version 12.0.5.  I keep being offered an "Update" to 12.0.4 and am puzzled.  How can I turn off this offer or should this update be applied?

    I have Photoshop cs5, version 12.0.5 x32 installed on a Widows box.  I keep being offered an "Update" to 12.0.4 and am puzzled.  How can I turn off this offer or should this update be applied?  If it should be applied how to do it.  When I try it, the update fails.
    Thanks!

    I found the answer in another forum thread...

  • What is thermo and new puzzle quiz in could backup

    when I go to manage back up on my ipad/iphone there are 2 things I see - Thermo and New Puzzle quiz, what are these things? Also when you click edit with these you get the option to "delete all" what does that do?

    The 3.0.8 version includes both bug fixes and feature enhanchements. The release notes contain a listing of new features.

  • What is difference between == and equals ??? i wanna know in detain example

    Hi
    1) String s1 = new String("abs");
              String s2 = s1;
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    Output:
    true
    true
    2)
    String s1 = new String("abs");
              String s2 = s1;
              s2 = "abs";
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    output:
    false
    true
    i m not getting that here s1 is object and its assigned to s2 object so both are point to same memory location...but while assinging s2 = "abs" which is same as s1 then its behave like different object y?

    but while assinging s2 = "abs" which is same as s1 then its behave like different object"abs" is "the same as" s1 in the sense that it represents the same characters in the same order. But it is also different from s1 in that it refers to a different object. It's the same distinction as you get comparing two $20 notes: they are equal but, since there are two of them they cannot be identical.
    With Java reference variables this equal/indentical distinction is represented by equals()/==.
    In general each class defines its own equals(). (Much as there will be a legal definition what what counts as being equal to $20.) This realationship is generally what you mean and hence the rule "when comparing objects use equals()".

Maybe you are looking for

  • How to install ORAESB and ORAWSM schema

    I installed oracle database 10.2. I'm not clear as to how to install ORAESB and ORAWSM schemas which are required for SOA Suite 10.1.3 installation.

  • Make DW default for XML files?

    I'm sure there's a way to do this that I'm missing, but I'd like to make DW my default app for XML files.  I know how this can be done on Windows (using "open with" and changing default), but I'm using Mac OSX.  I tried messing with the file types se

  • Creating a first time site

    what is a good stage size for building a web site in flash...... I use to know the pixel dimensions but since I have been out of the loop I totally forgot. also I want to create "growing effect" in that I have these really artsy curly lines I created

  • Some Users cannot Open Workflow Approval Task

    We have a SPD workflow published to our production site and it includes a 'Start Approval Process' task which involves a number of users (determined by a lookup to another list) this worked brilliantly until we republished the workflow with some mino

  • Many issues in Crystal Reports for VS 2005 Pro

    <p>Hi All,</p><p> Got a few questions...</p><p>I just upgraded to VS 2005 Pro from VS 2003 pro. I find that there's alot of "bugs" or perhaps someone could point out some possible common errors I might have done... </p><p>First thing that got to me w