Clarity On Overriding Equals Method

Oct 2, 2014

For a few days I've been reading about the importance of overriding the equals method. How overriding it actually determines or checks the values stored in the variable. I realize that you can check the values stored in the primitive datatypes with "==", and when you don't override the equals method it acts the same way, right? When used with a reference datatype, "==" or the default equals() method only compares, or sees, if the variable is pointing to the same instance of a class. For some reason, in the examples, what is taking place to actually check the values stored inside the variables.

Here is part of an example (I've added comments for things that are confusing me):

@Override
public boolean equals(Object obj) {
//So we use Object here instead of the class type
// we're overriding this equals method for?
Is this so that we can use it to check different types? (overloading?)
if (obj == this) {
return true;

//Isn't this checking to see if the calling object is the same as the object we're passing to it?
Why doesn't this return false?
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}

//How exactly do we check the values stored in each object though?
}

View Replies


ADVERTISEMENT

Overriding Equals Method - Cannot Invoke Equals On Primitive Type (double)

Jan 7, 2014

I am trying to override the equals method for my class TeamMember I have two fields:

private Details details;
private double salary;

Code for override I get an error on salary saying cannot invoke equals (double) on the primitive type (double)

Is their something I am missing/coding wrong?

Java Code:

public boolean equals(Object obj) {
//test exceptional cases
//avoid potential NullPointerException/ClassCastException
if ((obj == null) || (this.getClass() != obj.getClass()))
return false;
TeamMember other = (TeamMember) obj; //cast to a TeamMember object
// compare fields details and salary
return this.details.equals(other.details)
&& this.salary.equals(other.salary);
} mh_sh_highlight_all('java');

View Replies View Related

Overriding Equals Method From Object Class

May 5, 2014

I am attempting to override the equals method from the Object class which checks if two variables point towards the same object. I want the method to check if if the argument being passed in(an object) has the same data(instance variables) as the object that's calling this method. A NullPointerException is being thrown; Here is the code.

package javaapplication5;
import java.text.NumberFormat;
import java.util.Scanner;
import java.lang.Object;
public class Product {
private String product;
private String description;
private double price;

[Code] ....

And here is the stack trace

Exception in thread "main" java.lang.NullPointerException
at javaapplication5.Product.equals(Product.java:42)
at javaapplication5.Product.main(Product.java:24)
Java Result: 1

View Replies View Related

Equals Method - Take Object Reference And Return True If Given Object Equals This Object

Mar 28, 2014

Create an equals method that takes an object reference and returns true if the given object equals this object.

Hint: You'll need 'instanceof' and cast to a (Geocache)

So far I have:

public boolean equals(Object O){
if(O instanceof Geocache){
Geocache j=(Geocache) O;
if (this.equals(j)) //I know this is wrong... but I can't figure it out
return true;
}

else return false;
}

I think I have it correct up to the casting but I don't understand what I'm suppose to do with the this.equals(). Also I'm getting an error that I'm not returning a boolean... I get this all the time in other problems. I don't get why since I have to instances of returning booleans in this. "returns true if the given object equals this object" makes no sense to me. I assume the given object, in my case, is 'O'. What is 'this' object referring to?

View Replies View Related

Altering Parent Method Behavior By Overriding Method It Calls

Apr 21, 2014

I have two classes (Daughter and Son) that contain some very similar method definitions:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();
d.speak();
s.speak();

[Code] .....

Each of those classes has a "speak" method with two out of three lines being identical. I could move those into a parent class, but I need each of the child classes to continue to exhibit its unique behavior. I'm trying the approach below, which replaces the unique code with a call to a "placeholder" method that must be implemented by each child class:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();

[Code] .....

This works and moves the shared code from two places (the Daughter and Son classes) into one place (the new Mother class, which is now a parent class of Daughter and Son). Something about this feels a bit odd to me, though. It's one thing for a child class to override a parent class's methods to extend or alter their behavior. But, here, I've implemented an abstract method in the parent class to alter what happens when the parent class's method (speak(), in this case) is called, without overriding that parent class method itself.

View Replies View Related

Overriding Static Method

Aug 30, 2011

class One
{
public static void doStuff()
{
System.out.println("One");
}
}

class Two extends One

[code]....

My understanding of static says that static methods cannot be overrriden but the compilation of the above code results in Overriding rule violation error.

View Replies View Related

Return Statement In Method Overriding

Jan 1, 2015

class Base
{
public Base rtc() {
System.out.println("am in parent");
return new Base();
}
}
class Ret extends Base

[Code] ....

Output :

I am in child class but b1.rtc requires b2 to hold the return value y not Ret's object.

View Replies View Related

Overriding Java ToString Method For Web Browser

Mar 14, 2014

How do i print override the toString for WebBrowser as i would like to print out the object bc. Tested the program and it is fine if i put it in the main method rather than the WebBrowser constructor.

import java.util.*;
class ListNode <E> { /* data attributes */
private E element;
private ListNode <E> next;
/* constructors */
public ListNode(E item)
{ this(item, null);

[code]...

View Replies View Related

Overriding In Java - Foo Method Of Class X Is Not Throwing Compile Error

Jul 29, 2013

class SubB{
public void foo(){
System.out.println(" x");
}
}
public class X extends SubB {
public void foo() throws RuntimeException{
super.foo();
if(true) throw new RuntimeException();
System.out.println(" B");
}
public static void main(String [] args){
new X().foo();
}
}

Why the foo method of class X is not throwing a compile error because according to the override rule, if the superclass method has not declared exception, the subclass method can't declare a new exception...

View Replies View Related

Getting Error On Equals Method For Objects

Mar 26, 2014

I have to create a class that has two fields. One called length and the other width. I have to make a method that returns the tract area. Similarly, I also have to make a method that indicates whether two objects have the same fields. Here is the code that I have assembled...so far

// create private fields to hold width and length
private double width;
private double length;

[Code].....

My problem is encountered when writing that equals method

if(length.equals(object.length) && width.equals(object.width))

I get an error saying HTML Code: cannot invoke equals(double) on the primitive type double. Meanwhile, I do see, to realize that when I change my fields to capital "Double." The problem disappears; however, in my class I have never dealt with a situation where I have to use capital d in double. In fact, I don't even know what's the difference between Double and double. I do know what double is but not the other one..

View Replies View Related

Netbeans - Unable To Debug Equals Method

Mar 11, 2015

I need to debug the equals method implementation of a class I've made, but I cannot for the life of me get Netbeans' debugger to step into it. I can step into other methods from the class (most of which implement the methods in an interface) that are called in the main method (just like the equals method). I've tried...

-Disabling all the step filters
-Clearing the Netbeans cache
-Moving the call to the equals method out of the if statement it's in and just calling it as its own statement
-placing breakpoints within the equals method as well as on the call to the method
-placing a method breakpoint on the overridden equals method in addition to the other locations
-Using the shift-F7 version of the step into command

I'm using Netbeans 8.0.1 (I don't know if this is the latest version, but the last time I tried to update everything died and I had to completely remove NB and reinstall it) and JDK 8u05 (I think).

View Replies View Related

Creating Equals Method To Compare Strings In A Class?

Mar 26, 2015

How would I create a equals method to compare strings in a class that I'm creating. I need to create the method in my class, and then call it in a driver. How would I do this?

View Replies View Related

How To Test And Finish ToString And Equals Method In Code

Jan 19, 2014

Write a class encapsulating the concept of a course grade, assuming a course grade has the following attributes: a course name and a letter grade. Include a constructor, the accessor and mutator, and methods toString and equals.Write a client class to test all the methods in your class.

how to test and finish the toString and equals method in this code ?

package labmodule7num57;
import java.util.*;
public class LabModule7Num57 {
// Constructors//
private String name;
private String letterGrade;
public LabModule7Num57 (String name,String letterGrade) {

[code]....

View Replies View Related

JAVA Calculator - Equals Method To Return Appropriate Value Using Standard Arithmetic

Apr 18, 2014

I am having trouble using the equals method to return the appropriate value using standard arithmetic.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

[Code] ....

I know that "inText.setText(Integer.toString(secondOperand));" in the code is wrong, I just don't know the right code...

View Replies View Related

Overriding Inherited Methods

Feb 5, 2015

So the first thing I would like to ask about is overriding inherited methods. I am asked to override methods in one of my assignments and I am not really sure how to go about doing it.

View Replies View Related

Warning For Not Overriding Methods

Mar 26, 2014

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
/* display selected number
if selected, bg is green
if not selected bg is pink
*/

[code]....

my compiler is telling me that the getList... method is not being overridden.but when I change the JList<String> to JList and Object to String in the parameters, i get a warning from the compiler that it's an "unchecked call".

View Replies View Related

Overriding CompareTo From Comparable Interface

Oct 31, 2014

Here is my code:

/*
* Implement the Comparable interface on objects of type Order.
* Compare orderId, then productId. The lesser orderId should come first. If the orderIds match, then the lesser productId should come first.
*/

@Override
public int compareTo(Order ord) {
// TODO Auto-generated method stub
if(orderId > ord.orderId){
return 1;

[Code] ....

Here is the output:

Actual: 0
Expected: -1
Actual: -1
Expected: -1
Actual: 1
Expected: 1
Actual: 1
Expected: 1
Actual: 0
Expected: 0
Actual: 0
Expected: 0

In short, the "Actual" is what my code produces and the "Expected" is what it is supposed to produce. As you can see, only the first one is mismatching... I'll admit, the comment section above the method is confusing and I wasn't exactly sure what it wants me to do, but I thought I figured it out. I just don't see how 5/6 of these tests can work and the 6th one not.

View Replies View Related

Overriding ToString - Indicate Whether Coin Is Face Up Or Down

Jan 2, 2015

what im trying to do is modify the Coin class to override the toString() method so that it indicates whether the coin is face up or face down. For example, "The coin is face up." This is what i have so far:

public class Coin {
public static void main(String[] args) {
Coin coin = new Coin();
for (int i = 0; i < 1; i++) {
coin.flip();
System.out.println(coin);

[Code] .....

View Replies View Related

Overriding - Use Public Access Modifiers With String

Apr 2, 2015

Why do we use public access modifiers with String toString() method in java while overriding???

View Replies View Related

Do While Loop - Using Equals?

Sep 30, 2014

having a hard time with my do while loop. for some reason in my else if structure it will break when i using .equals in the do while loop. But if i try doing tmp == "D" || tmp == "d" it will keep looping how can i go about using alternative for .equals?

Here is my code:

do {
Object object = new Object();
System.out.println("For a deposit Enter: D
Withdrawal Enter: W
"
+ "or 'Quit' to exit.");
String tmp = input.next();
if (tmp.equals("D"))

[Code] ....

View Replies View Related

HashCode And Equals Implementation

May 15, 2014

Its that very old question regarding hashcode and equals implementation which i am not getting .

import java.util.*;

public class MyElement {
public static void main(String a[]){

HashSet<Price> lhm = new HashSet<Price>();
lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));

[Code] .....

In the above program even if i comment out the Hashcode method , i believe it is still taking the memory address values from the native hashcode method of Object class. but the equals override implentation says that i have two insertions which are same . So as per my logic it should not allow the duplicate element to enter.but its not so ...the duplicate element is well inserted without hashcode .

View Replies View Related

Equals Comparison Does Not Work

Jan 12, 2015

All I am trying to do is to make a section of code execute if two strings are equal. The two strings are userId and "A001062". When I use the debugger in Eclipse, I can see the value of userId as "A001062" but whatever string comparison I try never evaluates to true. I have tried

userId=="A001602"
userId.equals("A001602")
"A001602.equals(userId)
Assigning A001062 to a string called AAA and comparing userId to AAA

My code is as follows. I have also attached a screen shot from the Eclipse Debugger which makes me think the string comparison should succeed. I never see the debugger execute the print line nor do I see the print line on the JBOSS console.

String userId = StringUtils.trim(nextLine[HR_USER_ID]);
String AAA="A001062";
if (userId.intern().equals(AAA.intern())) {System.out.print("MKP1: " + userId+"-"+managerId);}
if (userId.compareTo("DTS0428")==0) {System.out.print("MKP2: " + userId+"-"+managerId);}

Attached image(s)

View Replies View Related

Average Of Numbers With Sentinel Value Equals To 0

Mar 27, 2014

(Count positive and negative numbers and compute the average of numbers). Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.

I moved the different boolean statements around, but I'm not getting the sentinel value to end the run. It continues to let me add integers endlessly. The code I wrote is below:

package exerciseFourOne;
import java.util.Scanner;
public class AverageOfIntergers {
public static void main(String[] args) {
// TODO Auto-generated method stub
int positive = 0; // number of positive integers
int negative = 0; // number of negative integers
int sum = 0; // value of sum of integers

[Code] .....

View Replies View Related

Equals Signature / Constructors And Arguments

Jul 14, 2014

In Java code, write class called Student with the following features:

• a private instance variable int studentNumber that is initialized to zero.
• a private instance variable String firstName;
• a private instance variable String lastName;
• a constructor which takes an integer argument and two String arguments to initializes the three respective data items.
• a public method with signature equals(Student s) . . .

So far this is my code :

public class student {
private int studentnumber = 0;
public student () {
firstname= "forename":
lastname="surname":
public student (integer studentnumber, string firstname, string lastname) {
this.firstname= firstname
this.lastname= lastname:

My question is how do i add the integer in the argument do i have to use int =? and how would i go about doing the public signature equals...

View Replies View Related

Roman To Arabic Converter Says Everything Equals 1

Mar 25, 2015

Im working on a roman numeral to arabic converter and all I had to do was fill out the conversion method romanToDecimal. But for some reason no matter what number I enter It always says my number is equal to one.

//Quiz 1 EC
import java.util.*;
class Roman {
private String romanNum;
private int decimalNum;
public Roman(){
romanNum = "I";
decimalNum = 1;

[code]....

View Replies View Related

While Loop - How Result Being Replace If It Only Equals To 1

Jul 6, 2014

I was reading a book and came across this while loop.

public class Powers {
public static void main (String [] args){
int e;
int result;
for(int i = 0; i < 10; i++){

[Code] .....

This loop presents the following (I'm sure it's not necessary):

2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512

I am just having a difficult time understand and grasping this concept. My main issue is result *=2; this is making it very difficult to understand. How is result being replace if it only equals to 1.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved