If I want to compare C, D, and E how do I do that with an equals method?

public class Fraction {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	
		
	
		{
		Fraction c, d, e;
		c = new Fraction(5, 8);
		d = new Fraction(1, 2);
		e = new Fraction(5, 8);
		if (c.equals(d))
		{
		System.out.println("c == d");
		}
		if (c.equals(e))
		{
		System.out.println("c == e");
		}
		} // end main
	}
}

Recommended Answers

All 13 Replies

You need to implement equals() method inside your class. If you implement equals(), you may need to implement hashCode() (or hashValue()??) for it as well... For now, equals() may be enough...

You need to implement equals() method inside your class. If you implement equals(), you may need to implement hashCode() (or hashValue()??) for it as well... For now, equals() may be enough...

ok so what would that look like?

public class Fraction {
  /**
   * @param args
   */
  public static void main(String[] args) {
    // your implementation
  }

  public boolean equals(Fraction other) {
    // implement the comparison here
    // return true if self & other are equal
    // return false otherwise
  }
}

I tryed that and I still have an error or something wrong with it. I still see
"The constructor Fraction(int, int) is undefined"

should the equals method corrected that?

O and the quick fixes in eclips dont help either.

public class Fraction {


	public Fraction(int i, int j) {
		// TODO Auto-generated constructor stub
	}
	/**
	 * @param args
	 */
	  public static void main(String[] args) {   
		  // your implementation
		  
	  }   public void equals(Fraction other) {  
		  // implement the comparison here    
		  // return true if self & other are equal   
		  // return false otherwise  }}
		Fraction c, d, e;
		c = new Fraction(5, 8);
		d = new Fraction(1, 2);
		e = new Fraction(5, 8);
		if (c == (d))
		{
		System.out.println("c == d");
		}
		if (c == (e))
		{
		System.out.println("c == e");
		}
	

		} // end main
	}

this is what I have come up with your help. however I still can not get the output to out put c == e

Your variable c, d, and e cannot be compared because there is no comparison. Also, using "==" will attempt to compare reference of object which will NEVER be the same unless you are comparing either primitive (with the same value) or the same object itself.

Because you are relying on Eclipse which does not teach you how to program in Java... You are missing the class's variables to store your incoming fraction. Then you still do not implement the 'equals()' method I have mentioned in my previous post...

You should read a tutorial before you attempt to jump in like this... One site here seems to be OK.

I will give you a sample code below just this time for what you are doing...

public class Fraction {
  int num1;
  int num2;

  /**
   * Constructor
   */
  public Fraction(int i, int j) {
    num1 = i;
    num2 = j;
  }

  /**
   * @param args
   */
  public static void main(String[] args) {   
    Fraction c = new Fraction(5, 8);
    Fraction d = new Fraction(1, 2);
    Fraction e = new Fraction(5, 8);

    if (c.equals(d)) {
      System.out.println("c == d");
    }
    if (c.equals(e)) {
      System.out.println("c == e");
    }
  } // end main

  /**
   * Return true if the incoming Fraction object's num1 and num2 are equal to
   * self's num1 and num2 respectively.
   *
   * @param  other  a Fraction object to be compared with self
   * @return  boolean of class's comparison
   */
  public boolean equals(Fraction other) {
    return (num1==other.num1 && num2==other.num2);
  }
}

// Note: A flexible equals() may check for Comparable also.
//       This check does not expect any inheritance.
//       It will become very difficult if you also consider inheritance.

First thank you for your help so far, your better than my Corse instructor. Second this is for a java Corse. Their idea is to throw us code and make it work with little to no help. my instructor says " if you don’t know how to do something GOOGLE it"

You may look at my edited above and learn a bit from the sample. The equals() method is not really for beginners to implement because it involves many things in depth which are important later on. I don't think that your instructor is right in this case...

WOW yes your correct I would have never figured that out on my own. I can’t believe that they really expect us to know this is a 100 level course.


Thank you.

Member Avatar for ztini

Java NOOB, allow me to explain about comparing objets:

Fraction a = new Fraction(4, 5);
Fraction b = new Fraction(4, 5);

a.equals(b) // false;

They are separate objects in memory. Fraction a has its own piece of memory and Fraction b has its own piece. Invoking .equals() checks whether or not the memory locations are equal, so in this case they are not.

However, if you do:

Fraction c = a;
a.equals(c) // true;

They both point to the same piece of memory. So how do you compare 2 objects that may be equal?

Fraction d = (3, 2);
Fraction e = (3, 2);

d.equals(e) // false;

One way to do this is with the Comparable interface and implement the compareTo() method. This will allow you as the developer to tell the compiler how these objects should be compared.

Here is a simple example:

public class Fraction implements Comparable<Fraction> {
	
	private int n, d;
	
	public Fraction(int n, int d) {
		this.n = n;
		this.d = d;
	}
	
	@Override
	public int compareTo(Fraction that) {
		if (this.n == that.n && this.d == that.d) 
			return 0;
		else if ((double) this.n / this.d  < 
				(double) that.n / that.d)
			return -1;
		else 
			return 1;
	}
	
	public static void main(String[] args) {
		
		Fraction a = new Fraction(2, 5);
		Fraction b = new Fraction(4, 5);
		Fraction c = new Fraction(4, 5);
		
		a.compareTo(b); // -1
		b.compareTo(c); // 0
		c.compareTo(a); // 1
	}

}

You can read more about the compareTo method here and why it returns -1, 0, and 1. Basically, you just need to define what constitutes one object as being equal to another, being less than, or greater than.

Implementing the Comparable interface allows your objects to be used in data models like priority queue. Simply overriding the Object method .equals() does not account for this.

@ztini
I disagree with the explanation you made below...

Fraction d = (3, 2);
Fraction e = (3, 2);

d.equals(e) // false;

If you are using equals(), you are NOT supposed to compare object's reference. If the result is false, it should be comparing as followed.

Fraction d = (3, 2);
Fraction e = (3, 2);

d==(e) // false;

Comparable and compareTo() is a bit more advance than using only equals(), but it is related. However, beginners should not be learning this right now because it will be very confused unless they already know enough OO programming concept.

I'm hesitant to leap in here, but there's a bit of confusion that should be cleared up.

In ztini's post, he says that "invoking .equals checks whether or not the memory locations are equas". This is true, if you have not written a .equals() method for your class, and assuming you're not extending an object that overrides the .equals() inherited from Object. This is because your class is ultimately derived from Object, which means that it inherits the methods that Object defines. If you have not overridden those methods, what you get is what Object does.

For .equals, what Object does is to simply compare the memory location stored in the reference variable. This, as ztini says, compares objects for identity: if they are both pointing at the same area of memory, they are identical, and therefore equal.

That is almost never what you want to happen. What you want is to define equality for your object in such a way that .equals() returns true just in the case that the comparand is equal to the object on which the method is called.

What defines equality is simply what is important to the person writing or using the class. If you have a Line object, you might be concerned about the length only, or the slope only, or the length and the slope, or if you're writing a graphics application, the length, slope, thickness, and color, or you might be concerned about location as well. I have no way of knowing what's important to you about your Line. But whatever is important to you, the form of an equals() method is typically something like this:

class Line{
public boolean equals(Object o)
{
  if (this == 0) return true;  // identical objects are equal
  if (! 0 instanceof Line) return false;  //if it's not a Line, it's not equal to this line
  Line l = (Line) o; // we can't get here if o isn't a Line, so cast
  if (l.getFeature1() != this.feature1) return false; //whatever features you're 
  if (l.getFeature2() != this.feature2) return false; //interested in
  ...

  return true;  // if you've compared on all interesting parameters and made it through, they're equal
 }
}

So all you're doing is checking the obvious cases, then comparing on every detail that you care about, then returing true if it passes all of your tests.

Taywin mentioned overriding hashCode() - this is important, if you're going to be putting these objects into a HashMap or something, but leave it. For now, just remember: don't expect good performance from a HashMap unless you've dealt with hashCode().

ztini mentioned the Comparable interface. This is a kettle of fish of a different color! Here, you're not just saying "this thing is/is not equal to that one" - you're defining how they should be placed in order. You have, say, two Lines, and you want to sort them. Comparable allows you to define which one is less than and which is greater than the other. In the process, you're also going to define how you return a result of equal.

Comparable is only implemented for classes that have a natural ordering to them, the equals() method should be implemented for anything that you might compare to something else at some point. Don't get them mixed up, they're actually quite different things - the only place they interact is that if you do implement Comparable, your equals() method can simply look like this:
public boolean equals(Object o)
{
return this.compareTo(o) == 0;
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.