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?
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.
Exception in thread "main" java.lang.NullPointerException at javaapplication5.Product.equals(Product.java:42) at javaapplication5.Product.main(Product.java:24) Java Result: 1
Here is my code the whole program is working correctly but the Boolean equals and the has code and it is a requirement for the assignment. Why it is not working.
I know there are issues with the code I am new with java and was struggling so I have to clean my code up before I submit the assignment but for right now I have the out put the way I want it except the Boolean and hash code methods always output that the rectangles aren't equal even when I know they are and it outputs the not equal statement twice??
Now lets say that I want to access a method 'addInterest()' that is in the 'SavingsAccount' class I would have to do: '((SavingsAccount)s).addInterest();'
The question I have is why do I have to cast 'b' to SavingsAccount? Isn't the actual object reference of 'b' already an instance of 'SavingsAccount' class? How does the 'BankAccount' affect the object itself? I'm really confused as to what class is truly getting instantiated and how BankAccount and SavingsAccount are both functioning to make the object 'b'.
I don't understand why the object reference variable 'a' cannot be recast from a thisA object reference to a thisB object reference.Is it the case that once a reference variable is linked to a particular object type then it cannot switch object types later on.I am facing the Java Associate Developer exam soon and I am just clearing up some issues in my head around object reference variable assignment,
class thisA {} class thisB extends thisA { String testString = "test";} public class CastQuestion2 { public static void main(String[] args) { thisA a = new thisA(); thisB b = new thisB();
How do i take input values for TwoDPoint (which are objects) and return it back in numerical values also print them.
When i create an object in main method and pass values to my function of return type TwoDPoint,it gives error:- found int,int need TwoDPoiint,TwoDPoint.
// Here is what i tried to do:
Created class TwoDPoint that contains two fields x, y which are of type int. Defined another class TestTwoDPoint, where a main method is defined.In the main method created two TwoDPoint objects.
Then I modified the class TestTwoDPoint and add another function to it. This function takes two TwoDPoints as input and returns the TwoDPoint that is farthest from the point (0,0).
Then I added another function to TestTwoDPoint. This function takes two TwoDPoints as input and returns a new TwoDPoint whose x value is the sum of x values of the input TwoDPoint's and whose y value is the sum of the y values of the input TwoDPoint's.
class TwoDPoint { int x = 2; int y = 4; } class TestTwoDPoint { public static void main(String args[]) { TwoDPoint obj1 = new TwoDPoint(); System.out.println(obj1.x); System.out.println(obj1.y);
I'd like the code that would return an object's human readable name.ie. myObject.getObjectsName();Which would return the name of the object That is, the name of the object that I use as I code.In the code below, I'm trying to find the correct code to return the string,btnTTT_01..The results of the testing follow.
public static void main(String []args) { tictactoe game ; game = new tictactoe(); game.setVisible(true); System.out.println ("main") ; System.out.println ( "game.getName() is: " + game.getName() ) ; System.out.println ( " " );
I've been trying to learn Java for the last 36 hours or so (after applying for a HTML/CSS job saying "Java knowledge preferred"), and decided to experiment a bit making a graphical tic-tac-toe game. I eventually managed to get that done and it's working. Working code below:
[Java] tic tac toe 1 - Pastebin
So, it works to an extent, however, the way I am capturing which cell is selected seems very sloppy, and would not work if the cells weren't squares or rectangles. So I made a copy of the project and restructured it adding the mouse event to the cells, but now I can't get JComponent to repaint. New code below:
tic tac toe 2 - Pastebin
Curiously, clicking triggers the action for all 9 cells, but I presume it's because I haven't bounded them making it think I've clicked all 9 simultaneously.
What I've tried:
Make the Cell class extend the game class and call this.repaint()- causes stack overflow.
Calling Game.GameState() within the cell clicking event and making that function static - compiler doesn't like calling repaint() inside a static function.
Making another class to make a clone of the Game object and then refresh- was never going to work....
I am doing a Junit test case, but I keep having issues with AssertEquals ( object expected, object actual). I don't know how to reference the other actual object so that it can compare to the expected.
public void add (Distance d) throws CustomException { //I can also convert feet to inches and add all inches together and then divided inches to feet and inches Distance result = new Distance(); int newFeet = this.feet + d.getFeet(); int newInches = this.inches + d.getInches(); if(newInches > 11) { newFeet = newFeet + (newInches/12);
I have started working on a little project in my free time. It is just a simple text rpg that runs in a counsel window. I have 5 files each file contains 1 class.
public class SomnusCharacter { private String gender = ""; private int age = 0; private String race = ""; private int level = 0; private int xp = 0;
[Code] ....
The chain of events right now is:
1. MainMenu is run 2. If user inputs n CreateCharactor is run 3. User inputs name, age, ect in SomnusCharacter object made in CreateCharacter 4. Intro (just rough demo for testing purposes) is run 5. If user inputs m Menu is run 6. Menu calls and prints out all the information from the object made in CreateCharacter
Step 6 is where I am having my problems. How can I reference (lets say the SomnusCharacter object made is called player) player from my Menu class? I know that if I made a new character that it would just create another SomunsCharacter object with the default values again.
I read somewhere : "Java use clone() method of Object class to copy content of one object to the other. The problem will arrive if the Class that needs to be copied also contains reference to the other object."Not able to understand the second line.
Check out the following basic code (assume that dog has a method called bark):
Dog d = new Dog(); Object o = d;
o.bark(); // error
But why? Isn't o just a pointer to a memory address which has the dog object? If so, why can't the compiler see that the object has a method called bark? Or, to ask the question another way, why is Java designed to check the object reference to see if the method exists instead of the object itself?
I am new to Java and have read books, the Java docs, and searched the Internet for my problem to no avail. I have an Array of objects that contains strings. How can I get the object's strings to print in a list so that the user can select that object to manipulate its attributes? For example, the user can select "Guitar 1" from a list and manipulate its attributes like tuning it, playing it, etc. I have a class called Instruments and created 10 guitar objects.Here is the code:
Instrument [] guitar = new Instrument[10]; for (int i = 0; i < 10; i++) { guitar[0] = new Instrument("Guitar 1"); guitar[1] = new Instrument("Guitar 2"); guitar[2] = new Instrument("Guitar 3"); guitar[3] = new Instrument("Guitar 4"); guitar[4] = new Instrument("Guitar 5"); guitar[5] = new Instrument("Guitar 6");
I am trying to get this to where I can type in a name and it will search through each object and print back the corresponding object info.
Java Code:
import java.util.Scanner; public class MyPeople { public static void main(String[] args) { Person[] p = new Person[] { new Person("Chris", 26, "Male", "NJ", "Single"), new Person("JoAnna", 23, "Female", "NJ", "Single"), new Person("Dana", 24, "Female", "NJ", "Single"), new Person("Dan", 25, "Male", "NJ", "Single"), new Person("Mike", 31, "Male", "NJ", "Married") };
Task:The main method of the class Things below creates an object called printer deriving from the class PrintingClass and uses that object to print text. Your task is to write the PrintingClass class.
Program to complete: import java.util.Scanner; public class Things { public static void main(String args[]) { String characterString; Scanner reader = new Scanner(System.in); PrintingClass printer = new PrintingClass(); System.out.print("Type in the character string for printing: "); characterString = reader.nextLine(); printer.Print(characterString); } }
// Write the missing class here
Note: In this exercise the solution is part of a conversion unit where many classes have been declared. Because of this the classes are not declared as public using the public attribute.
Example output
Type in the character string for printing: John Doe
John Doe
My Class: class PrintingClass { public void print(){ System.out.println(characterString); } }
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
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..
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? }
public class CollisionManager<T> { private boolean collision = false; private T mainEntity; public <T extends Entities> void handleCollision(T mainEntity, T secondEntity){ this.mainEntity = mainEntity; // This is illegal. } }
Why "this.mainEntity = mainEntity" is incorrect and also show me the correct way to achieve this?
The error I am getting is "Type mismatch: cannot convert T to T"
I have just started working with linked lists. I have a linked list of Objects and I want to be able to search for a specific object. But currently my code continues to return false. Also how would I go about removing the first index of the linked list.
public static void main(String[] args) { LinkedList<Cookies> ml = new LinkedList<>(); int choice = 0; while (choice >= 0) { choice = menu();
I am reading Head First: Java and got to Object References. In the book I got a little bit confused on what happens when two object reference's point at the same object so I wrote a small crude test, the below code. This of course clarified what happens but what I am interested in knowing is in what circumstances would you want to have two separate references for the same object when you could just use the original? Eg. v1
class ObjectValue{ int objVal = 1; } class ObjectValueTestDrive{ public static void main(String [] args){ // "Value of v# should be" refers to if it copied the given object values, instead of referencing the same object ObjectValue v1 = new ObjectValue(); System.out.println("Value of v1 should be 1:" + " "+ v1.objVal);
Explain anonymous objects with example clearly...i read some where anonymous objects advantage is saving memory...it is benificiable when there is only one time object usage in our program..i can't understand one time usage of object ....i know anonymous objects but i don't know in which context we use them in our programs...i did the anonymous object program with my own example but i can't differentiate this one with normal object..i'm providing my own example below
//anonymous object public class anonymous { int x=10; int y=25; void display() { System.out.println("anomymous");