FAQ Database Discussion Community


Java Compare 2 integers with equals or ==?

java,int,compare,equals
i am very very new to Java and i would like to know how can i compare 2 integers? I know == gets the job done.. but what about equals? Can this compare 2 integers? (when i say integers i mean "int" not "Integer"). My code is: import java.lang.*; import...

equals() method not working

java,equals
The equals() method should check if the dimensions of the first box and the cube are the same. How to fix it? It currently does not work. The program returns the message "illegal start of type" at if. I am new to this plz help public class testNew { public...

Java contains() not in accordance with equals()

java,equals,contains
I have a custom class with overriden equals() and hashCode() methods. I store instances of that class in a TreeSet. I cannot figure out why the tree.contains(someObject) returns true, while tree.first().equals(someObject) returns false, in the case when the tree has only one element.

Check objects equality without equals overriding in java [closed]

java,unit-testing,equals
Are there any utils in java which allow to check objects equality without equals overriding? For some reasons I don't want to provide my class with equals method. I need something like SomeUtils.equals(a,b) in my unit test which compares all object fields (via reflection I guess).

Equals method for PlayingCard Class, how to get working?

java,oop,equals
I have been working on a PlayingCard class, and I am having difficulty writing an equals() method for the class. The intent for the equals method is to compare two playing cards to see if they are identical or not. I have used an example from the Big Java Late...

setting objects equal to eachother (java)

java,methods,compiler-errors,equals
So I have a class called Person which looks like this public class Person { private String personName; public String toString(){ return personName; } public Person(String personName){ this.personName = personName; } } and another class in which I am creating the object(s) person public class IdanJavaTask { public static void...

How to override hashcode and equals method to avoid adding duplicate strings in HashSet in java?

java,equals,hashcode,hashset,java-collections-api
In my code I have a set of PlacesInfo object ie., Set<PlacesInfo> placeId; In this set I am adding placeId (String). I need to avoid adding duplicates to my HashSet. Here is my override method below. but, still it is adding duplicate elements to my set. So, how to avoid...

C#, Which class fields/members should be considered when overriding GetHashCode and Equals?

c#,equals,gethashcode,iequatable
There is this excelent question and answer about this topic: Do I HAVE to override GetHashCode and Equals in new Classes? As it mentions: you only need to override them if you need value equality semantics. The System.Object implementation isn't 'bad', it just only does a reference check (which is...

Duplicate values in a hashSet

java,equals,hashcode,hashset
I am trying to count the number of combinations of 1, 5, 10 and 25 that sum to n. Given that I don't want any repetitions (like 1+5 = 6 and 5+1 = 6). I am using a hashSet. I implemented a class named ResultSet that saves the number of...

Java equals() and hashCode() changes

java,object,equals,hashcode
What problems can arise if the result of the equals() and hashCode() methods changes across the lifetime of an object? Thank you!...

R - Get row numbers where two matrices have equal rows

r,matrix,find,rows,equals
I have to matrices and I want to no which rows are identical. Lets say I have a matrix A which looks like this: A = matrix(1:12, 4, 3, byrow=T) [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [4,] 10 11 12 a...

Writing an equals() method for linked list object

java,linked-list,equals
I'm having trouble with an equals(Object other) method within a class I'm building called LString. The class contains an object called LString that builds strings out of linked lists, and a few other methods. I'm working on two methods, compareTo() and equals(). The class is tested by running another file,...

how i can make my variable equal any element of my Array? [closed]

java,android,arrays,random,equals
I have String[] country={"USA","ks a","UK","France"}; I have a variable String z. I want to say if(z.equals(any element of my array (USA or ks or France) but randomly: if(z.equals(country[i]){ Doing action any code } Can anybody help me?...

comparing two dates. Equal isn't working as well

sql,date,ms-access,compare,equals
I've got trouble with comparing two dates: There is short datetime field in database, recorded by Microsoft Access 2002-2003 data extension (#yyyy/mm/dd#). When I tried to compare via operators "greater than" and "less than" it works fine, but when I replaced with the operator "equal" it's giving me an empty...

Optimize performance of a equal method to mark multiple rows in a DataGrid

c#,.net,wpf,datagrid,equals
I've the following method: private void SelectingCoreItems(SortedList<ICoreItem, ICoreItem> sortedList) { for (int i = 0; i < VisibleCoreItems.Count; i++) { CoreItem currentItem = VisibleCoreItems[i]; if (sortedList.ContainsKey(currentItem)) { itemListView.SelectedItems.Add(currentItem); } } } I want to mark all equal items. That works, but the performance is very bad because the sortedList contains...

How does a hashSet admit elements

java,equals,hashcode,hashset
I have a list of objects that I need to add to a HashSet, say List<Node> books. Say further that no two books are equal in the very sense that their equals method would each return false; say, however, that their hashCode method each return 1. I am using this...

Java - remove objects in a collection that are in another collection, with an arbitrary meaning of “equals”

java,collections,equals
This is very easy if I just want to base this on absolute equality. I'd just do: collectionA.removeAll(collectionB). However, let's say I have this object: class Item { private String color; private String name; private String type; } And two collections... List<Item> items1, List<item> items2. ...but I just want to...

Javascript if statement if (ball.style.left === '0px') {

javascript,css,if-statement,equals,semantics
I think the problem is really simple, but I'm not seeing it. I just want to move the "ball" to the left 132.5px when I click the "dice" and if the ball is 0px left. I think the if statement is wrong!! Can someone help me? var ball = document.getElementById('ball');...

Issue with .equals()

java,split,equals
Following is a small section of the code I am using, along with the syntax of the text file I am using. (I am fairly sure both are grossly overcomplicated, but I am not exactly sure how to simplify them.) while((line = bufferedReader.readLine()) != null) { if(line.split("@@")[0].equals(lineNumber)) { numberOfLines =...

Java: Map with doubleKey type, how to make the right hashCode()?

java,dictionary,equals,hashcode,multikey
I have a MultiKey object as keys for a Map. A Key consists of a Name (String) and an ID (int). The following contract has to be fullfilled: Keys have to be equal if either the names of both keys are equal or the ids of both keys. How do...

Annotating a Java class as safe for reference comparison

java,intellij-idea,equals,equality,multiton
I have a class that's a multiton, so I know that given a particular key, there will never be two instances of the same class that exist. This means that, instead of: if (someObject.equals(anotherObject)) ...it's safe for me to do this: if (someObject == anotherObject) The class is also final,...

How to check a spinner which contains a string is not equal to another string?

android,equals,android-spinner
How to validate many spinners,which intially contains string select.If it is changed,then only validation must execute.Otherwise have to display some message. if(!(spnVehType.getSelectedItem().toString()) .equals ("Select")|| !(spnVehType.getSelectedItem().toString()).equals("اختيار") && !(spn_bodytype).equals("Select")|| !(spn_bodytype).equals("اختيار") && !(spn_veh_make).equals("Select")|| !(spn_veh_make).equals("اختيار") && !(spn_veh_model).equals("Select")||...

How to compare two JSON strings when the order of entries keep changing [duplicate]

java,json,string,equals,jsonobject
This question already has an answer here: Compare two JSON objects in Java 15 answers I have a string like - {"state":1,"cmd":1} , I need to compare this with generated output but in the generated output the order keeps changing i.e. sometimes its {"state":1,"cmd":1} other times its {"cmd":1,"state":1}. Currently...

Why is the input parameter of Equals of type Object?

c#,equals
I've overridden Equals(Object input) thousands of time and never contemplated the matter deeper. Now, after a few drink, I started to think about it and it stroke me that I'm not entirely certain why it's so. Equality operation is semantically speaking checking if two thingies are a copy of itself....

why use null != anything instead of anything!=null? [duplicate]

java,null,equals
This question already has an answer here: object==null or null==object? 9 answers I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too "true".equals(x). Why is...

Java questions on equals and compareTo method

java,linked-list,equals,compareto
Hi I'm very new to Java and have this problem with 2 methods operating on linkedList. The find function I have wrote always return false. The find method is to take a type E element as argument, and returns true if the item is in the linked List, or false...

Lua - Is it possible to check if 2 functions are equal?

function,lua,byte,equals
Is it either possible to get the size of a function in bytes to see if it matches another function similar to C++ sizeof operator, or evaluate two functions some other way to see if they are both equal without actually knowing what the function/s are? Example: local function equals(func1,...

Can/should one write a Comparator consistent with Object's equals method

java,equals,comparator
I have an object, Foo which inherits the default equals method from Object, and I don't want to override this because reference equality is the identity relation that I would like to use. I now have a specific situation in which I would now like to compare these objects according...

Understanding equals method

java,equals
J. Bloch in his effective Java provides a several rules for the implementation for equals method. Here they are: • Reflexive: For any non-null reference value x, x.equals(x) must return true. • Symmetric: For any non-null reference values x and y, x.equals(y) must return true if and only if y.equals(x)...

when to implement comparable and when to implement equals in Java

java,equals,hashcode,comparable
In Java, when should I implement Comparable<Something> versus implementing the equals method? I understand every time I implement equals I also have to implement hash code. EDIT Based on answers I am getting below: Is it safe to say that if I implement Comparable then I don't need to implement...

Maintaining hashCode contract for the specific condition, equals() depending on two integers

java,equals,hashcode
I have a basic class with the structure: class Employee { int eId; String eName; Employee(int id, String name) { this.eId= id; this.eName= name; } The conditions for equality is such that equals() should return true if any of the following is true: eId are same. eName are same. Lengths...

EqualsIgnoreCase function - Exception : org.apache.pig.backend.executionengine.ExecException

apache-pig,equals,ignore-case
EqualsIgnoreCase function - Exception : org.apache.pig.backend.executionengine.ExecException Input : a.csv ------- a A (blank/empty line) b B c C Objective : To select the records which are 'a', 'A', 'b' and 'B'. Approach 1 : A = LOAD 'a.csv' using PigStorage(',') AS (value:chararray); B = FILTER A BY LOWER(value) IN ('a','b');...

Floated Sidebar: How to get sidebar full height of window?

css,height,equals,viewport,sidebar
I know that there will be people that may ask for the full code, but I'm just asking in a very general sense. Say, I have the main content floated to the left with no fixed height and the sidebar floated to the right. I want the sidebar to take...

Is there any negative consequence in having Equals based on GetHashCode?

c#,.net,equals,gethashcode
Is the following code OK? public override bool Equals(object obj) { if (obj == null || !(obj is LicenseType)) return false; return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { return Vendor.GetHashCode() ^ Version.GetHashCode() ^ Modifiers.GetHashCode() ^ Locale.GetHashCode(); } All the properties are enums/numeric fields, and are the only...

Java how does HashMap identify the key object if hashCode are the same and equals is true?

java,hashmap,equals
I always thought hat HashMap is identifying its keys by using hasCode and equals. But this code still does not give me the value back. What am I missing? import java.util.HashMap; import java.util.Map; /** * Created by kic on 25.04.15. */ public class TypePair { private final Class a; private...

Overriding equals and hashCode on a POJO with a List object

java,apache,equals,hashcode
I have a 2 POJOs that look like this public class Element{ private String name; private int number; //GETTERS AND SETTERS } public class Container{ private String subject; private String email; private List<Element> elements; //GETTERS AND SETTERS } And I need to verify if two Container objects are the same....

calling super.equals() in derived class while overriding equals

java,inheritance,equals,overriding
I have a base class with age and name as instance members and derived class with bonus. I am overriding equals in Derived class. I know how equals works in Java when there is a single base class. But I am not able to understand how it works in case...

How to write a by-the-book equals() method, possibly with hashCode()? [duplicate]

java,oop,netbeans,equals,hashcode
This question already has an answer here: What issues should be considered when overriding equals and hashCode in Java? 12 answers How would you write an equals() method? I need to be able to write a useable one for comparing playing cards in the program. I am using NetBeans...

Slow dictionary with custom class key

c#,string,dictionary,equals,gethashcode
I have a custom class that I was trying to use as a key for a dictionary: // I tried setting more than enough capacity also... var dict = new Dictionary<MyPoint, MyPoint>(capacity); Now let me be clear, the goal here is to compare two SIMILAR but DIFFERENT lists, using X,...

Is there any difference between == null and .equals(“null”)?

java,string,equals
I am confused about the following code. Why does it compare with both == and equals method? (validFolderRow.getBondTAFolderType() == null || validFolderRow.getBondTAFolderType().equals("null")) What's the difference between equals() and ==? Can anyone tell me what is the difference between validFolderRow.getBondTAFolderType() == null and validFolderRow.getBondTAFolderType().equals("null") ?...

Costs of binary operations

binary,equals,operation
I've ask myself if its cheaper to use >= than ==. Besides, that >= would be more secure in my case, which is a loop, adding objects to a list. The list itself always increase just by one, so a == would trigger. It, for sure, does not affect any...

Java ArrayList indexOf returns -1

java,arraylist,equals,indexof
I have a strange problem with my code. Heres the code I test the Chunk class with: List<Chunk> chunks = new ArrayList<Chunk>(); chunks.add(new Chunk(1,1,1)); System.out.println(chunks.indexOf(new Vector3i(1, 1, 1))); And here is the Chunk class' equals method: public boolean equals(Object object) { System.out.println("Test _1_"); if (object != null && object instanceof...

Comparing wrapper class with primitive using equals() gives strange behavior

java,wrapper,equals
Consider below code snap. we use equals() to compare objects are meaningfully equivalent or not ? Here both value are meaningfully equal but why does longWrapper.equals(0) return false ? And when I compared both value with == operator it returns true. Long longWrapper = 0L; long longPrimitive = 0; System.out.println(longWrapper...

Should I override the Object.equals(Object) method?

java,equals,equality,object-comparison
I have two instances of the same class. public class Gilda { private String nome; public Gilda(String nome) { this.nome = nome; } // More stuff } When trying to compare them via Object.equals(Object) method, it returns false. This is strange because nome has the same value on both of...

Java Linked List .contains method

java,list,equals,contains
I have a LinkedList containing elements of type A. I need to check whether the list contains an element based on some criteria. Is it enough to override the .equals method in class A, or do I need to override the hash method as well?...

Implementing hashCode for a BST

java,binary-search-tree,equals
In Java to compare two objections for equality, you must implement both the equals method and the hashCode method. I need to compare two BSTs for equality. How do I implement the hashCode method in such a case? Now, implementing the hashCode on the Node class is simple enough: imagine...

Comparasion of Integer.equals() and Objects.equals()

java,testing,equals
Here are my test for two equals methods: Random generator = new Random(); long startTime = System.nanoTime(); for(int i = 0; i<1000; i++) { Integer int11 = generator.nextInt(1000); Integer int22 = generator.nextInt(1000); int11.equals(int22); } long endTime = System.nanoTime(); long duration = (endTime - startTime); System.out.println(duration + " ns"); Random generator1...

how to combine the elements of a list representing the elements of a Bash command to a new list featuring the equals symbol

python,list,command,arguments,equals
I have a list like the following: commandOptionsAndArguments = ['myBigTool', '--num-callers', '30', '--leak-check', 'full', '--tool', 'memcheck', '--suppressions', 'etc/valgrind-root.supp', '--suppressions', 'Gaudi.supp/Gaudi.supp', '--suppressions', 'oracleDB.supp', '--suppressions', 'valgrindRTT.supp', '--suppressions', 'root.supp/root.supp', '--mySpecialFlag', '$(which python)', '$(which athena.py)', 'athenaConf.pkl'] This list consists of elements of a Bash command featuring options and, if they have them, their respective...

Implementing equals and hashcode for a BST

java,equals,hashcode
This question is sort of a follow up to Implementing hashCode for a BST. My question was poorly thought through and so I got an answer that I am not sure how to use. I need to implement equals for a BST: so that iff two BSTs are equal in...

Why doesn't or operator work in if statement when using “not equals”?

c#,equals,operator-keyword
I am a bit confused by this. I want to hide a button if the current username of the system is != Administrator OR Administrator2, but the only way to get my desired goal is by using the && instead of ||. string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; if (userName != @"PC\Administrator"...

Why assertEquals and assertSame in junit return the same result for two instances same class?

java,junit,equals,assert
According to documentation assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. So I am expecting that if I have a class like below class SomeClass {} then SomeClass someClass1= new SomeClass(); SomeClass someClass2= new SomeClass(); assertSame(someClass1,someClass2); // fail assertEquals(someClass1,someClass2); // fail...

Cannot resolve method equals(java.lang.Long)

java,equals
The following code gives error (with IDEA) while I think it shouldn't. Long[] a = {0L, 0L}; Long[] b = {1L, 1L}; if((a[0] + a[1]).equals(b[1])) System.out.println("Equal"); Says cannot resolve method equals(java.lang.Long). But it works well with if(a[0].equals(b[0])). I thought that plus operator would return a Long object. Why does it...

How can I check if an ArrayList contains an Object with a specific field value?

java,arraylist,override,equals,contains
I have an ArrayList of Objects. I want to see if that ArrayList contains an Object with a particular field. TeamBuilder.java public class TeamBuilder { public static void main(String[] args) { Team team = new Team(); team.addMember(new TeamMember("myID")); System.out.println(team.containsMember("myID")); //false } } TeamMember.java public class TeamMember { private String id;...

How to make java interface / abstract class that uses per-field equals instead of default equals?

java,design,hash,equals
I have a process which requires creating java classes which will serve as keys in a table (as a key in a Spark framework). To get the correct functionality, I need to override the default object equals() and hash code methods with functions that perform field-wise comparison. (I generate this...

Hangman game; why doesn't .equals work? [closed]

java,string,equals
I'm doing a hangman game, I don't necessarily need alternatives to achieve this but I have a piece of code that doesn't return an error but it also doesn't work. for (int i = (length - 1); i >= 0; i--) { if (guess.equals(result.charAt(i))) { System.out.println("There is an " +...

How can I get the return value of a superclass method without executing it?

java,equals,hierarchy
This is my superclass equals() method: public boolean equals(Object other){ Car c = (Car)other; if(this.make.equals(c.make) && this.model.equals(c.model)){ System.out.println("True, Cars are equal"); return true; } else System.out.println("False, Cars are not equal"); return false; } Here is my subclass equals() method: public boolean equals(Object other) { GreenCar g = (GreenCar) other; if(super.equals(g)==true){...

How to compare two Strings when both can be null? [duplicate]

java,equals,equality
This question already has an answer here: Compare two strings in Java with possible null values 8 answers I am aware that it is better to call the equals method over using the == operator (see this question). I want two strings to compare as equal if they are...

How hashset checks for duplicate elements?

java,equals,hashcode,hashset
Kindly look into my code : HashSet<A> set = new HashSet<A>(); for (int i = 0; i < 10; i++) set.add(new A()); System.out.println(set.contains(new A())); Class A is defined as : class A { public boolean equals(Object o) { return true; } public int hashCode() { return (int) (Math.random()%100); } }...

Check CMTime Equals

objective-c,time,compare,equals,cmtime
Is there any method to check a CMTime is equal to another CMTime. In my case I need to check CMTime is equal to KCMTimeZero. I tried CMTimeCompare method, but it will be True for all the CMTimes which is equal to KCMTimeZero or greater than KCMTimeZero.