Why am I getting this error about the compareTo method? - java

I am trying to understand the compareTo method. I wrote this class AboutcompareTo, but i am stuck in why/how i get this error?- the code is nearly finished.
anyone can explain in details what i am doing wrong. Thanks
the code:
public class AboutCompareTo {
public static void main(String[] args) {
Fruit[] fruits = { new Fruit(2), new Fruit(3), new Fruit(1) };
java.util.Arrays.sort(fruits);
}
}
class Fruit implements Comparable<Fruit> {
private double weight;
public Fruit(double weight) {
this.weight = weight;
}
#Override
public int compareTo(Fruit o) {
Fruit f = (Fruit) o;
if (Fruit > o.Fruit) // <-- the error
return 1;
else if ((Fruit < o.Fruit)) // <-- the error
return -1;
else
return 0;
}
}

The compareTo method compares an instance of your class, i.e. this Fruit, to an instance of another Fruit passed to you as a parameter. Therefore, the comparison needs to be between o's weight, and your own weight:
#Override
public int compareTo(Fruit o) {
if (this.weight > o.weight)
return 1;
else if (this.weight < o.weight)
return -1;
else
return 0;
}
Note 1: I used this.weight to refer to the weight of this Fruit. I did this to point out that weight attribute belongs to this instance; however, you can omit this. from the expression, i.e. use weight > o.weight instead.
Note 2: I assume that you did this for a learning exercise. For production code Java class library provides a pre-built method for comparing doubles - i.e. Double.compare. You can rewrite the method in a single line:
#Override
public int compareTo(Fruit o) {
return Double.compare(weight, o.weight);
}

Related

Java Deep Comparison Returns False when Comparing a Deep Copy

I created an abstract class Fruit, which overrides the equals() method. Then I created a subclass, Orange, which overrides the copy() and the equals() method. In my test file, TestFruit.java, I am creating an array of oranges and testing their methods. I am trying to create a deep copy of orange and do a deep comparison between the parent orange and the copy. However, in my output, the comparison always returns false. I checked the parent and the copy's attributes and they do seem to be the same. Any pointers would be appreciated. I am pretty new to Java and copying. I attached my code below.
Fruit.java:
package juicer;
import copy.Copyable;
public abstract class Fruit implements Copyable, Cloneable
{
private double mass;
private boolean isJuicedRemoved;
protected Fruit(double theMass)
throws IllegalMassException
{
{
if (theMass <= 0)
{
throw new IllegalMassException(theMass);
}
else
{
this.mass = theMass;
this.isJuicedRemoved = false;
}
}
}
protected Fruit(Fruit fruit)
{
this.mass = fruit.mass;
this.isJuicedRemoved = fruit.isJuicedRemoved;
}
public double getMass()
{
return mass;
}
public boolean getIsJuicedExtracted()
{
return isJuicedRemoved;
}
protected void setMass(double value)
{
this.mass = value;
}
protected abstract double juiceRatio();
public double extractJuice()
{
double liquidMass = amountJuice();
if (!isJuicedRemoved)
{
isJuicedRemoved = true;
mass -= liquidMass;
}
return liquidMass;
}
public double amountJuice()
{
if (isJuicedRemoved) return 0.0;
return mass * juiceRatio();
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Fruit.
// If it is not, then return false.
if (!(obj instanceof Fruit)) return false;
// Step 2: Cast obj to an Fruit.
Fruit rhs = (Fruit)obj;
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj) && // test for equality in the super class
mass == rhs.mass &&
isJuicedRemoved == rhs.isJuicedRemoved;
}
#Override
public int hashCode()
{
int result = super.hashCode();
result = 31*result + Double.hashCode(mass);
result = 31*result + Boolean.hashCode(isJuicedRemoved);
return result;
}
#Override
public Object clone() throws CloneNotSupportedException
{
Fruit objectClone = (Fruit)super.clone();
objectClone.mass = mass;
objectClone.isJuicedRemoved = isJuicedRemoved;
return objectClone;
}
#Override
public String toString()
{
return "\tmass = " + mass +
"\n\tisJuiceExtracted = " + isJuicedRemoved + "\n";
}
}
Orange.java:
package juicer;
public class Orange extends Fruit
{
public Orange(double mass)
{
super(mass);
}
// copy constructor
public Orange(Orange other)
{
super(other);
}
#Override
protected double juiceRatio()
{
return 0.87;
}
#Override
public boolean equals(Object obj)
{
// Steps to override the equals() method():
// Step 1: Test if obj is an instance of Orange.
// If it is not, then return false.
if (!(obj instanceof Orange)) return false;
// Step 2: Cast obj to an Orange.
// This step is not needed since the only data fields this
// class has are the ones it inherits.
// Step 3: Test if the data fields of the invoking object are
// equal to the ones in rhs using a deep comparison
// and return this result.
return super.equals(obj);
}
#Override
public Object copy()
{
return new Orange(this);
}
#Override
public String toString()
{
return "Orange:\n" + super.toString();
}
}
TestFruit.java:
package test;
import juicer.*;
import java.util.Random;
public class TestFruit
{
public static void main(String[] args)
{
Orange[] oranges = new Orange[1];
//Random double generator for mass
Random rd = new Random();
//create oranges
for (int i = 0; i <= oranges.length - 1; i++ )
{
oranges[i] = new Orange(rd.nextDouble());
}
for (Orange orange : oranges)
{
Orange orangeCopy = new Orange(orange);
if (orange == orangeCopy)
{
System.out.print("The comparison is true!");
}
else
{
System.out.print("Does not match.");
}
}
}
}
One of the common misconceptions in Java is the use of == vs .equals(). When you use == to compare two objects in Java, internally it's comparing its memory address. == does not actually call .equals().
In this case, you have two distinct orange objects, so the comparison will always return false.
If you use a.equals(b), then it will actually invoke your equals method which you implemented.
As #Andreas pointed out in the comments, there's another issue. Calling super.equals(obj) in Fruit will call the superclass implementation of equals, and the superclass of Fruit is Object. Object.equals() behaves the same as == (i.e. also checking for reference equality). Overriding .equals() is not trivial, so it can often be nice to have the IDE generate it for you.
In contrast with a language like C++, Java does not have operator overloading. This means that you can't define a different implementation for ==. This is why it's best practice to always call .equals() when comparing any non-primitive types (unless you're explicitly checking reference equality, which is rare).

New integer is equal to the difference of 2

I'm coding something for a theoretical airport case study and I need help with one bit. I've got 2 different integers with names: maxfuelCapacity and fuelCurrent, and I need something that says ' fuel needed to pump is '.....' being the difference between the maxfuelCapacity of the plane and the current amount. There are no real values so far. How do I go about doing that?
public static int maxfuelCapacity;
public int fuelCurrent;
public String name;
Boolean parked;
public String[] Plane = {
"BA103", "BA493", "BA209"
};
public void setName(String n) {
name = n;
}
public void setParked(Boolean o) {
parked = o;
}
public int getInt(String Maxfuelcapacity) {
return maxfuelCapacity;
}
public String getInt1 (String fuelCurrent) {
return fuelCurrent;
}
As has been mentioned in the comments, your method would look like:
public int fuelNeeded(int fuelCurrent, int maxfuelCapacity) {
if(fuelCurrent >= maxfuelCapacity) {
System.out.println("The tank already has enough");
return 0;
}
return maxfuelCapacity- fuelCurrent;
}
So you call this method in your main function that does the calculation.

Interface and type casting

In the Java 8 tutorial about interface, one example says that when a class implements an interface, one has to type cast the interface type into the class type in order to invoke methods of this class, as shown by the following example from the java 8 tutorial:
public class RectanglePlus
implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}
In the method isLargerThan(Relatable other), other is casted to type RectanglePlus in order to invoke getArea().
In the other example about default methods in interface, the compareTo(Card o) method doesn't type cast o to type PlayingCard, but can invoke int hashCode() directly, I don't understand this. Thanks for your help.
package defaultmethods;
public class PlayingCard implements Card {
private Card.Rank rank;
private Card.Suit suit;
public PlayingCard(Card.Rank rank, Card.Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Card.Suit getSuit() {
return suit;
}
public Card.Rank getRank() {
return rank;
}
public boolean equals(Object obj) {
if (obj instanceof Card) {
if (((Card)obj).getRank() == this.rank &&
((Card)obj).getSuit() == this.suit) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public int hashCode() {
return ((suit.value()-1)*13)+rank.value();
}
public int compareTo(Card o) {
return this.hashCode() - o.hashCode();
}
public String toString() {
return this.rank.text() + " of " + this.suit.text();
}
public static void main(String... args) {
new PlayingCard(Rank.ACE, Suit.DIAMONDS);
new PlayingCard(Rank.KING, Suit.SPADES);
}
}
In short: Because hashCode is defined in java.lang.Object and every other class extends Object implicitly.
So when you have
public int compareTo(Card o) {
return this.hashCode() - o.hashCode();
}
the compiler already knows that o is of type Card which extends Object which defines a hashCode method. No need for an explicit cast.
On the other hand in your isLargerThan method the parameter is of type Relatable:
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
And judging from the link you provided, the getArea method is defined in RectanglePlus only. Since the compiler only sees Relatable it does not know anything about a getArea method at this point and you need to explicitly cast other to RectanglePlus to be able to access it.
Note that you should actually do an instanceof check before casting to avoid a ClassCastException when other is not a RectanglePlus (you don't know if there might be other classes implementing Relatable).
Let me try a non-code related example:
If people have a pet they usually give it a name. So whatever pet you have, one can always ask for its name (cf. hashCode). But they cannot ask you to make it bark (cf. getArea) unless they know that it is a dog.
And you will probably fail to make a cat bark (cf. ClassCastException).

Java inheritance ( local variable/ boolean in if)

I am studying the inheritance (Java), and I wrote the following code. The first part is the CarBase, and then I created a childclass 1, called Bus.
My idea is that first make a judgement if it is a bus, and by doing that, I need a boolean [if(isBus)], but when I wrote this code in Eclipse, there is a error message, said 'isBus can not be resolved to a variable'.
Could some one please tell me how to solve this problem? Do I need to declare the boolean variable first?
Another question is about the declaration of local variables.
In the getOnBus(0 method, I have a local variable called temp,I was taught that whenever using a local variable insided a method, I need to declare it first and then I shall be able to use it, but I saw someone use it directly like the following, I was wandering what's the difference between the two?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus(int p_amount) {
if(isBus) {
int temp = 0; // <===
temp = current_Passenger + p_amount; // <===
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
or if there is difference if I use it without declaring it?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if(isBus) {
int temp=current_Passenger+p_amount; // <====
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The code is as following
First Part CarBase(parent)
public class CarBase {
public int speed;
public String name;
public String color;
public int maxSpeed = 90;
// Method
public void speedUp(int p_speed) {
int tempSpeed = 0;
if (p_speed > 0) {
tempSpeed = speed + p_speed;
}
if (tempSpeed <= maxSpeed) {
speed =tempSpeed;
}
}
}
Second Part Bus (Child1)
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if (isBus) {
int temp = 0;
temp = current_Passenger + p_amount;
if (temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The point in using inherance is to abstract whether an object is a Car or a Bus, and write code that works no matter what is passed. To do so, you use abstract methods. Consider
abstract class Vehicle {
private int occupied;
public Vehicle() {
occupied = 0;
}
public abstract int getCapacity(); // number of passengers
public boolean board(int howmany) {
if (occupied+howmany <= capacity) {
occupied += howmany;
return true;
}
else
return false;
}
public void unboard(int howmany) {
occupied -= howmany;
}
};
class Car extends Vehicle {
public Car () { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 5; }
}
class Bus extends Vehicle {
public Bus() { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 32; }
}
you'd write every function to accept a Vehicle, and deal with it without the need to know if it is a bus or a car. (the following is a dumb function, just to give you an example)
void board_on_first_avaible(Vehicle[] x, int n) {
for (int i=0; i<x.length; x++)
if (x.board(n))
return true; // board ok
return false; // couldn't board on anything
}
Note that you should design your code so that the functions are declared, abstract in Vehicle, for both Car and Bus. Thus getOnBus() would be a bad idea
OK for the first point "isBus" is not declared, i can not see the point of checking in this method as you already know u are extending the CarBase but if you need to check you can do it like this
if(this instanceof CarBase)
for the second point there is actually no effect for the change
int temp=0; // <===
temp= current_Passenger+p_amount; // <===
first you initialize with 0 then you assign the new value to it
int temp=current_Passenger+p_amount;
here you initialize the temp with the value
You don't need to check if the Bus object 'isBus()' .... it IS a Bus, because you are defining the class as Bus!
So... if you were to create a new Bus object, you would say something like:
Bus BigYellowBus0001 = new Bus();
if you were to then say:
BigYellowBus0001.getOnBus(10);
You would NOT need to check if BigYellowBus0001 is a bus.... right?
In fact, you don't even need to name the method getOnBus().... it could just be getOn.
I think maybe you've gotten off on the wrong foot by deciding that Bus is a subclass of Car.
As for local variables, this just means variable that begin and end inside the method... so you did that nicely with your 'temp' variable.
To show that you understand how to access variables of the superclass from the child class, you could check the speed of the bus before letting people on:
public boolean getOnBus (int p_amount){
if(speed = 0){
int temp=0;
temp= current_Passenger+p_amount;
if( temp > max_Passenger){
return false;
} else{
current_Passenger = temp;
return true;
}
}
return false;
}
isBus is not declared that reason why you got this error
You doesn't need this check, because this method declared for Bus class and you are sure what it IS a Bus not a parent CarBase class (please use Vechicle instead of CarBase, it's much better on my opinion)
In Java 0 is default value for int, so you don't need to init variable before assign new value
So you can simplify getOnBus() like that
public boolean getOnBus (int p_amount) {
int temp = current_Passenger + p_amount;
if (temp > max_Passenger) return false;
current_Passenger = temp;
return true;
}
To test if an object is an instance of a class you can to use variable instanceof YourClass which evaluates to a boolean

implementing and interfaces

I tried looking up tutorials and videos and I understand what implementing does, although I'm a bit confused as to how one would implement a class from the Java Library. In my homework, I'm suppose to utilize the class, DataSet and make it so it accepts Comparable objects. The program is suppose to record the Min and Max values depending on the objects, in this case, I'm suppose to use strings. I wasn't sure if I needed any classes to implement the Comparable interface, so I made two classes just in case I was suppose to do so. My real question is how do I actually incorperate a String variable in the tester class to actually read and compare the object to another? thanks in advance.
public class Word implements Comparable
{
private String str;
public Word()
{
str = null;
}
public Word(String s)
{
str = s;
}
public int compareTo(Object other)
{
String n = (String) other;
return str.compareTo(n);
}
}
I wasn't sure which of the two classes would be suitable for implementing Although i think the String class below would not work at all b/c It's already a standard class so I wasn't too sure about using it
public class String implements Comparable
{
public String s;
public String()
{
s = null;
}
public String(String str)
{
s = str;
}
public int compareTo(Object other)
{
String n = (String) other;
return s.compareTo(n);
}
}
public interface Comparable
{
public int compareTo(Object other);
}
public class DataSet
{
private Object maximum;
private Object least;
private Comparable compare;
private int count;
public DataSet(Comparable s)
{
compare = s;
}
public void add(Object x)
{
if(count == 0)
least = x;
if(count == 0 || compare.compareTo(x) >=0)
maximum = x;
else if(compare.compareTo(x) <0)
least = x;
count++;
}
public Object getMaximum()
{
return maximum;
}
public Object getLeast()
{
return least;
}
}
public class DataSetTester
{
public static void main(String[] args)
{
Comparable n = new Word("sand");
DataSet data = new DataSet(n);
data.add(new Word(man));
System.out.println("Maximum Word: " + data.getMaximum());
System.out.println("Least Word: " + data.getLeast());
}
}
An interface is a contract that showes that your class contain all methodes that are implemented in the interface. In this case the CompareTo(object other). The String class already implements the comparable interface so you don't need youre own class. I think your data set class should look something like this :
public class DataSet<T implements Comparable>
{
private T maximum;
private T least;
private T count;
public void add(T x)
{
if(count == 0){
least = x;
maximum = x;
}
else if(least.compareTo(x) > 0)
least = x;
else if(maximum.compareTo(x) < 0)
maximum = x;
count++;
}
public T getMaximum()
{
return maximum;
}
public T getLeast()
{
return least;
}
}
T is a generic type and in your case it should be String, Here is how you create a new Data set:
DataSet<String> ds = new DataSet<String>;

Categories