Search Results

Search found 1816 results on 73 pages for 'equals'.

Page 1/73 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to override equals method in java

    - by Subash Adhikari
    I am trying to override equals method in java. I have a class People which basically has 2 data fields name and age. Now I want to override equals method so that I can check between 2 People objects. My code is as follows public boolean equals(People other){ boolean result; if((other == null) || (getClass() != other.getClass())){ result = false; } // end if else{ People otherPeople = (People)other; result = name.equals(other.name) && age.equals(other.age); } // end else return result; } // end equals But when I write age.equals(other.age) it gives me error as equals method can only compare String and age is Integer. Please help me fix this. Thanks is Advance.

    Read the article

  • Java - abstract class, equals(), and two subclasses

    - by msr
    Hello, I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration. However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method? In summary, this is the code I have: public abstract class Xpto { } public class Person extends Xpto{ protected String name; public Person(String name){ this.name = name; } public boolean equals(Person p){ System.out.println("Person equals()?"); return this.name.compareTo(p.name) == 0 ? true : false; } } public class Car extends Xpto{ protected String registration; public Car(String registration){ this.registration = registration; } public boolean equals(Car car){ System.out.println("Car equals()?"); return this.registration.compareTo(car.registration) == 0 ? true : false; } } public class Teste { public static void foo(Xpto xpto1, Xpto xpto2){ if(xpto1.equals(xpto2)) System.out.println("xpto1.equals(xpto2) -> true"); else System.out.println("xpto1.equals(xpto2) -> false"); } public static void main(String argv[]){ Car c1 = new Car("ABC"); Car c2 = new Car("DEF"); Person p1 = new Person("Manel"); Person p2 = new Person("Manel"); foo(p1,p2); } }

    Read the article

  • overload Equals, is this wrong?

    - by Zka
    Reading some piece of code and I keep seeing this : public override bool Equals (object obj) { if (obj == null || this.GetType ().Equals (obj.GetType())) return false; //compare code... } Shouldn't it be like this (note the !): public override bool Equals (object obj) { if (obj == null || !this.GetType ().Equals (obj.GetType())) return false; //compare code... } Or does the equals perform differently in this case?

    Read the article

  • Overriding equals method without breaking symmetry in a class that has a primary key

    - by Kosta
    Hi, the answer to this question is probably "not possible", but let me ask regardless :) Assuming we have a very simple JAVA class that has a primary key, for example: class Person { String ssid; String name; String address; ... } Now, I want to store people in a collection, meaning I will have to override the equals method. Not a completely trivial matter, but on a bare basis I will have something along the lines of: @Override public boolean equals (Object other) { if(other==this) return true; if(!other.getClass().equals(this.getClass()) return false; Person otherPerson = (Person)other; if(this.ssid.equals(otherPerson.getSsid()) return true; } Excuse any obvious blunders, just typing this out of my head. Now, let's say later on in the application I have a ssid I obtained through user input. If I want to compare my ssid to a Person, I would have to call something like: String mySsid = getFromSomewhere(); Person myPerson = getFromSomewhere(); if(myPerson.equals(new Person(mySsid)) doSomething(); This means I have to create a convenience constructor to create a Person based on ssid (if I don't already have one), and it's also quite verbose. It would be much nicer to simply call myPerson.equals(mySsid) but if I added a string comparison to my Person equals class, that would break the symmetry property, since the String hasn't got a clue on how to compare itself to a Person. So finally, the big question, is there any way to enable this sort of "shorthand" comparisons using the overriden equals method, and without breaking the symmetry rule? Thanks for any thoughts on this!

    Read the article

  • Entity Framework 4 overwrite Equals and GetHashCode of an own class property

    - by Zhok
    Hi, I’m using Visual Studio 2010 with .NET 4 and Entity Framework 4. I’m working with POCO Classes and not the EF4 Generator. I need to overwrite the Equals() and GetHashCode() Method but that doesn’t really work. Thought it’s something everybody does but I don’t find anything about the problem Online. When I write my own Classes and Equals Method, I use Equals() of property’s, witch need to be loaded by EF to be filled. Like this: public class Item { public virtual int Id { get; set; } public virtual String Name { get; set; } public virtual List<UserItem> UserItems { get; set; } public virtual ItemType ItemType { get; set; } public override bool Equals(object obj) { Item item = obj as Item; if (obj == null) { return false; } return item.Name.Equals(this.Name) && item.ItemType.Equals(this.ItemType); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.ItemType.GetHashCode(); } } That Code doesn’t work, the problems are in Equals and GetHashCode where I try to get HashCode or Equal from “ItemType” . Every time I get a NullRefernceException if I try to get data by Linq2Entites. A dirty way to fix it, is to capture the NullReferenceException and return false (by Equals) and return base.GetHashCode() (by GethashCode) but I hope there is a better way to fix this problem. I’ve wrote a little test project, with SQL Script for the DB and POCO Domain, EDMX File and Console Test Main Method. You can download it here: Download

    Read the article

  • Findbugs warning: Equals method should not assume anything about the type of its argument

    - by Uri
    When running FindBugs on my project, I got a few instances of the error described above. Namely, my overriding versions of equals cast the RHS object into the same type as the object in which the overriding version is defined. However, I'm not sure whether a better design is possible, since AFAIK Java does not allow variance in method parameters, so it is not possible to define any other type for the equals parameter. Am I doing something very wrong, or is FindBugs too eager? A different way to phrase this question is: what is the correct behavior if the object passed to equals is not the same type as an LHS: Is this a false, or should there be an exception? For example: public boolean equals(Object rhs) { MyType rhsMyType = (MyType)rhs; // Should throw exception if(this.field1().equals(rhsMyType.field1())... // Or whatever }

    Read the article

  • Equals method of System.Collections.Generic.List<T>...?

    - by Sambo
    I'm creating a class that derives from List... public class MyList : List<MyListItem> {} I've overridden Equals of MyListItem... public override bool Equals(object obj) { MyListItem li = obj as MyListItem; return (ID == li.ID); // ID is a property of MyListItem } I would like to have an Equals method in the MyList object too which will compare each item in the list, calling Equals() on each MyListItem object. It would be nice to simply call... MyList l1 = new MyList() { new MyListItem(1), new MyListItem(2) }; MyList l2 = new MyList() { new MyListItem(1), new MyListItem(2) }; if (l1 == l2) { ... } ...and have the comparisons of the list done by value. What's the best way...?

    Read the article

  • Java: Comparing a class with another within that class using a my own .equals

    - by user1670252
    I am making a method .equals replacing the equals method used. It accepts a object. I want it to check if that object equals the class that runs the .equals class. I know I want to compare all the private methods I have to that object. Is there a way to do this without making another private class to get the private variables from the object? How do I do this to compare equality not identity? I am stuck on this. Do i have to use == to compare? Also looking online i see others use recursion. If this is the way i have to do it can you show and explain it to me? so an example i have public boolean equals(Object o) { this is in a class we will call bobtheBuilder (first thing to pop in my head) I want to check if the object o is equal to the class he has private object array and a private int. I assume I want to check if the array and int of this class equal the array and int of the object.

    Read the article

  • Should I forward the a call to .Equals onto .Equals<T>?

    - by Jaimal Chohan
    So, I've got you bog standard c# object, overriding Equalsand implementing IEquatable public override int GetHashCode() { return _name.GetHashCode(); } public override bool Equals(object obj) { return Equals(obj as Tag) } #region IEquatable<Tag> Members public bool Equals(Tag other) { if (other == null) return false; else return _name == other._name; } #endregion Now, for some reason, I used to think that forwarding the calls from Equals into Equals was bad, no idea why, perhaps I read it a long time ago, anyway I'd write separate (but logically same) code for each method. Now I think forwarding Equals to Equals is okay, for obvious reasons, but for the life me I can't remember why I thought it wasn't before. Any thoughts?

    Read the article

  • Consistent Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • Consistent HashCode() and Equals() results, but inconsistent TreeMap.containsKey() result

    - by smessing
    I have the following object Node: private class Node implements Comparable<Node>(){ private String guid(); ... public boolean equals(Node o){ return (this == o); } public int hashCode(){ return guid.hashCode(); } ... } And I use it in the following TreeMap: TreeMap<Node, TreeSet<Edge>> nodes = new TreeMap<Node, TreeSet<Edge>>(); Now, the tree map is used in a class called Graph to store nodes currently in the graph, along with a set of their edges (from the class Edge). My problem is when I try to execute: public containsNode(n){ for (Node x : nodes.keySet()) { System.out.println("HASH CODE: "); System.out.print(x.hashCode() == n.hashCode()); System.out.println("EQUALS: "); System.out.print(x.equals(n)); System.out.println("CONTAINS: "); System.out.print(nodes.containsKey(n)); System.out.println("N: " + n); System.out.println("X: " + x); } } I sometimes get the following: HASHCODE: true EQUALS: true CONTAINS: false N: foo X: foo Anyone have an idea as to what I'm doing wrong? I'm still new to all this, so I apologize in advance if I'm overlooking something simple (I know hashCode() doesn't really matter for TreeMap, but I figured I'd include it).

    Read the article

  • Overriding equals, hashCode and toString in a Clojure deftype

    - by mikera
    I'm trying to create a new type in Clojure using deftype to implement a two dimensional (x,y) coordinate, which implements a "Location" protocol. I'd also like to have this implement the standard Java equals, hashCode and toString methods. My initial attempt is: (defprotocol Location (get-x [p]) (get-y [p]) (add [p q])) (deftype Point [#^Integer x #^Integer y] Location (get-x [p] x) (get-y [p] y) (add [p q] (let [x2 (get-x q) y2 (get-y q)] (Point. (+ x x2) (+ y y2)))) Object (toString [self] (str "(" x "," y ")")) (hashCode [self] (unchecked-add x (Integer/rotateRight y 16))) (equals [self b] (and (XXXinstanceofXXX Location b) (= x (get-x b)) (= y (get-y b))))) However the equals method still needs some way of working out if the b parameter implements the Location protocol. What is the right approach? Am I on the right track?

    Read the article

  • Using UUIDs for cheap equals() and hashCode()

    - by Tom McIntyre
    I have an immutable class, TokenList, which consists of a list of Token objects, which are also immutable: @Immutable public final class TokenList { private final List<Token> tokens; public TokenList(List<Token> tokens) { this.tokens = Collections.unmodifiableList(new ArrayList(tokens)); } public List<Token> getTokens() { return tokens; } } I do several operations on these TokenLists that take multiple TokenLists as inputs and return a single TokenList as the output. There can be arbitrarily many TokenLists going in, and each can have arbitrarily many Tokens. These operations are expensive, and there is a good chance that the same operation (ie the same inputs) will be performed multiple times, so I would like to cache the outputs. However, performance is critical, and I am worried about the expense of performing hashCode() and equals() on these objects that may contain arbitrarily many elements (as they are immutable then hashCode could be cached, but equals will still be expensive). This led me to wondering whether I could use a UUID to provide equals() and hashCode() simply and cheaply by making the following updates to TokenList: @Immutable public final class TokenList { private final List<Token> tokens; private final UUID uuid; public TokenList(List<Token> tokens) { this.tokens = Collections.unmodifiableList(new ArrayList(tokens)); this.uuid = UUID.randomUUID(); } public List<Token> getTokens() { return tokens; } public UUID getUuid() { return uuid; } } And something like this to act as a cache key: @Immutable public final class TopicListCacheKey { private final UUID[] uuids; public TopicListCacheKey(TopicList... topicLists) { uuids = new UUID[topicLists.length]; for (int i = 0; i < uuids.length; i++) { uuids[i] = topicLists[i].getUuid(); } } @Override public int hashCode() { return Arrays.hashCode(uuids); } @Override public boolean equals(Object other) { if (other == this) return true; if (other instanceof TopicListCacheKey) return Arrays.equals(uuids, ((TopicListCacheKey) other).uuids); return false; } } I figure that there are 2^128 different UUIDs and I will probably have at most around 1,000,000 TokenList objects active in the application at any time. Given this, and the fact that the UUIDs are used combinatorially in cache keys, it seems that the chances of this producing the wrong result are vanishingly small. Nevertheless, I feel uneasy about going ahead with it as it just feels 'dirty'. Are there any reasons I should not use this system? Will the performance costs of the SecureRandom used by UUID.randomUUID() outweigh the gains (especially since I expect multiple threads to be doing this at the same time)? Are collisions going to be more likely than I think? Basically, is there anything wrong with doing it this way?? Thanks.

    Read the article

  • Does Scala's BigDecimal violate the equals/hashCode contract?

    - by oxbow_lakes
    As the Ordered trait demands, the equals method on Scala's BigDecimal class is consistent with the ordering. However, the hashcode is simply taken from the wrapped java.math.BigDecimal and is therefore inconsistent with equals. object DecTest { def main(args: Array[String]) { val d1 = BigDecimal("2") val d2 = BigDecimal("2.00") println(d1 == d2) //prints true println(d1.hashCode == d2.hashCode) //prints false } } I can't find any reference to this being a known issue. Am I missing something?

    Read the article

  • Overload the equals method in java

    - by fastcodejava
    Does anyone overload the equals method in java? The overloaded method will be public boolean equals(final MyClass myClass) This will have the benefit of having the relevant comparison part (guts of the method) in another method. Details are in this blog.

    Read the article

  • Using intermediate array for hashCode and equals

    - by Basilevs
    As its a pain to handle structural changes of the class in two places I often do: class A { private B bChild; private C cChild; private Object[] structure() { return new Object[]{bChild, cChild}; } int hashCode() { Arrays.hashCode(structure); } boolean equals(Object that) { return Arrays.equals(this.structure(), ((A)that).structure()); } } What's bad about this approach besides boxing of primitives? Can it be improved?

    Read the article

  • Overriding Equals method in Structs

    - by devoured elysium
    I've looked for overriding guidelines for structs, but all I can find is for classes. At first I thought I wouldn't have to check to see if the passed object was null, as structs are value types and can't be null. But now that I come to think of it, as equals signature is public bool Equals(object obj) it seems there is nothing preventing the user of my struct to be trying to compare it with an arbitrary reference type. My second point concerns the casting I (think I) have to make before I compare my private fields in my struct. How am I supposed to cast the object to my struct's type? C#'s as keyword seems only suitable for reference types. Thanks

    Read the article

  • Is it a bad idea if equals(null) throws NullPointerException instead?

    - by polygenelubricants
    The contract of equals with regards to null, is as follows: For any non-null reference value x, x.equals(null) should return false. This is rather peculiar, because if o1 != null and o2 == null, then we have: o1.equals(o2) // returns false o2.equals(o1) // throws NullPointerException The fact that o2.equals(o1) throws NullPointerException is a good thing, because it alerts us of programmer error. And yet, that error would not be catched if for various reasons we just switched it around to o1.equals(o2), which would just "silently fail" instead. So the questions are: Why is it a good idea that o1.equals(o2) should return false instead of throwing NullPointerException? Would it be a bad idea if wherever possible we rewrite the contract so that anyObject.equals(null) always throw NullPointerException instead?

    Read the article

  • Example of ==, equals and hashcode in java

    - by Abhishek Jain
    Given this: String s1= new String("abc"); String s2= new String("abc"); String s3 ="abc"; System.out.println(s1==s3); System.out.println(s1==s2); System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println(s3.hashCode()); Output is: false false true true 96354 96354 96354 Here == is giving false for each object but hashcode for each String object is same. Why is it so?

    Read the article

  • C++: call original definition of operator equals

    - by Luis Daniel
    I am overloading the operator equals (==) as show bellow: #include <string> #include <algorithm> bool operator == (std::string str1, std::string str2) { std::transform(str1.begin(), str1.end(), str1.begin(), ::tolower); std::transform(str2.begin(), str2.end(), str2.begin(), ::tolower); return (str1 == str2); } but, the problem appear on line return (str1 == str2), because operator == is called recursively. So, how can I call the original definition for operator equals (not the overloaded) ? Best regards

    Read the article

  • C#: How to gracefully pass multiple conditions to Equals()

    - by Roy
    I'm new to C#, and I'm trying to write a program that selects file types from a FileInfo list. So far I have something along the lines of: List<FileInfo> files = new List<FileInfo>(); IEnumerable<FileInfo> result = files.Where(f=>f.Extension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)|| f.Extension.Equals(".gif", StringComparison.InvariantCultureIgnoreCase) ); etc Obviously I'm not happy with this solution, but I don't know how to do this otherwise in a single call. What's the better way to go about it?

    Read the article

  • Generating equals / hashcode / toString using annotation

    - by Bruno Bieth
    I believe I read somewhere people generating equals / hashcode / toString methods during compile time (using APT) by identifying which fields should be part of the hash / equality test. I couldn't find anything like that on the web (I might have dreamed it ?) ... That could be done like that : public class Person { @Id @GeneratedValue private Integer id; @Identity private String firstName, lastName; @Identity private Date dateOfBirth; //... } For an entity (so we want to exlude some fields, like the id). Or like a scala case class i.e a value object : @ValueObject public class Color { private int red, green, blue; } Not only the file becomes more readable and easier to write, but it also helps ensuring that all the attributes are part of the equals / hashcode (in case you add another attribute later on, without updating the methods accordingly). I heard APT isn't very well supported in IDE but I wouldn't see that as a major issue. After all, tests are mainly run by continuous integration servers. Any idea if this has been done already and if not why ? Thanks

    Read the article

  • C#/Java: Proper Implementation of CompareTo when Equals tests reference identity

    - by Paul A Jungwirth
    I believe this question applies equally well to C# as to Java, because both require that {c,C}ompareTo be consistent with {e,E}quals: Suppose I want my equals() method to be the same as a reference check, i.e.: public bool equals(Object o) { return this == o; } In that case, how do I implement compareTo(Object o) (or its generic equivalent)? Part of it is easy, but I'm not sure about the other part: public int compareTo(Object o) { if (! (o instanceof MyClass)) return false; MyClass other = (MyClass)o; if (this == other) { return 0; } else { int c = foo.CompareTo(other.foo) if (c == 0) { // what here? } else { return c; } } } I can't just blindly return 1 or -1, because the solution should adhere to the normal requirements of compareTo. I can check all the instance fields, but if they are all equal, I'd still like compareTo to return a value other than 0. It should be true that a.compareTo(b) == -(b.compareTo(a)), and the ordering should stay consistent as long as the objects' state doesn't change. I don't care about ordering across invocations of the virtual machine, however. This makes me think that I could use something like memory address, if I could get at it. Then again, maybe that won't work, because the Garbage Collector could decide to move my objects around. hashCode is another idea, but I'd like something that will be always unique, not just mostly unique. Any ideas?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >