ToString array and equals method
I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
public String toString(){
//should indicate all cities
System.out.print("Cities :");
for (int i = 0; i < cities.length -1; i++)
return cities;
Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
public City getCity(String cityName){
//returns the City with name cityName (must search for city in the array)
//if the city does not exist, it returns null
for(int i = 0; i < cities.length; i++)
if(cityName.equals ("cityName"))
return ;
else return null;
Message was edited by:
ehj3000
great my world class is fixed now im getting missing return statements on the two methods
public City getCity (String cityName){
//returns the City with name cityName (must search for city in the array)
//if the city does not exist, it returns null
for(int i = 0; i < cities.length; i++)
if(cities.getName().equals(cityName))
return cities[i];
else
return null;
public String toString(){
//should indicate all cities
System.out.println("Cities: ");
for (int i = 0; i < cities.length -1; i++)
return cities[i].getName();
Similar Messages
-
Help need to know hashcode() and Equals method
Hi ,
Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
Please let me know briefly...........jverd wrote:
euph wrote:
jverd wrote:
euph wrote:
REFTY5_ wrote:
Hi ,
Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted. -
Scenario in which implement or Write our own hascode and equals method
Dear All,
Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
Thanks
SumitThanks for your reply
I have one more question.
When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
public class EqualsTest{
public EqualsTest() {
super();
public static void main(String[] args) {
Moof one =new Moof(8);
Moof two =new Moof(8);
if(one.equals(two))
System.out.println("one is equals to two");
class Moof {
private int moofvalue;
Moof(int val){
System.out.println("val inside moof constructor"+val);
moofvalue=val;
System.out.println("moofvalue inside moof constructor" +moofvalue);
public int getMoofValue()
System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
return moofvalue;
public boolean equals(Object o)
System.out.println("Object o in equals"+o);
if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
System.out.println("true");
return true;
else
System.out.println("false");
return false;
Here the output we get is :
val inside moof constructor8
moofvalue inside moof constructor8
val inside moof constructor8
moofvalue inside moof constructor8
Object o in equalsMoof@119c082
moofvalue inside getmoffvalue method 8
true
one is equals to two
The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
Thanks
Sumit -
When we override Hashcode and Equal Methods
Hi....I have doubt regading Hashcode and equal methods
why we override this two methods....
why we override hashcode method when we are overriding equal method,
i would very thankful to give answser
Thank you
Rameshhash code is computed to check the equality of two
objects ,
that is why if u change the default equal method
implementation , u need to change the hashcode method
as well.That's an incomplete answer at best.
The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia. -
Method Overriding-toString(),hashCode() and equals()?
Hi,
In some Java Classes, I saw that
toString()
hashCode()
equals()
these 3 methods of Object Class is overloaded.
I don't understand why and in what situation we have to override these 3 methods of Object Class.
Thanks in advance for ur Knowledge Sharing.
Regards,
S.PrabutoString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these. -
Use of hashCode and equals method in java(Object class)
What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.
You could find that out easily with google, that is a standard junior developer interview question.
-
Why do we need to override Hascode and Equals method?
Hi,
== checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
Please someone elaborate on this and also tell me what role hashcode plays in this.
thanks
Anirudhanirudh1983 wrote:
if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
The main rule is this: *objects that are equal() must have equal hashcodes*.
Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
Winston -
Do I need to override enum's hashCode() and equals()?
Hi all:
I have a enum type let's say it is
public enum Type
ONE,
TWO;
}If I want to compare the enum value to see if they are same value or not, let's say I have two:
Type a = Type.ONE;
Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
Can enum Type return the correctly hash code?
For example the class is like:
public Class A
Type type;
pubilc boolean equals(Object other)
// here skip check class type, null and class cast
if(other.type.equals(this.type))
return true;
else
return false;
public int hashCode()
int result = 31;
result += 31 * result + type.hashCode() ;
// can we get correct hash code from enum here?
return result;
}Answered by the test code by myself.
We can use either equals or (==) to see if they are the same value.
The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct -
String equal method Vs Object equal method.
hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.
RGEO wrote:
hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value. -
My Equal method is not working in array person!!! help me pls
My assignment is to create an application program that declares an array of 100 components of type person. add a person into the array and (CHECK DUPLICATE ENTRIES ARE NOT ALLOWED)
my code is(this is in another class):
public Boolean equals(Person p1){
return(name == p1.name&&address == p1.address&&telephoneNo == p1.telephoneNo&&email == p1.email);
Become(this is in my main class):
public static boolean isEquals(Person p1)
if(Person.getPersonCount()==1)
return false;
for(int i=0;i<Person.getPersonCount()-1;i++)
if(p1.equals(p))
return true;
return false;
my output code is:
public static void addPerson()
String name, address, telephoneNo, email;
int count=Person.getPersonCount();
int numberPerson = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter number of person you want to add in (1 to 100):","Person Adding Table",
JOptionPane.QUESTION_MESSAGE));
for(int i=0;i<numberPerson;i++)
name = JOptionPane.showInputDialog(null,"Please enter a person name:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
address = JOptionPane.showInputDialog(null,"Please enter a person address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
telephoneNo = JOptionPane.showInputDialog(null,"Please enter a person telephone number:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
email = JOptionPane.showInputDialog(null,"Please enter a person email address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
p[i+count]=new Person(name,address,telephoneNo,email);
if(isEquals(p[i+count]))
System.out.println("Please take note! Your person details have duplicate data...");
System.out.println("You has added "+numberPerson+" details of person!!!");Don't compare Strings with ==. Use the equals() method.
if (string1.equals(string2))Using == checks if they are the exact same object (think of it as the same location in memory). The equals() method checks if their contents are equal...just like you're trying to set up for your Person class. You want to see if the various fields of a Person object are the same...not if they are in fact the same object. -
Using equals method with an array?
Hello all,
I am attempting to use the equals method with an array and keep getting compiling errors. Could you please take a look at my code and tell me where I am going wrong:
if(board[row][col].equals(" "))
str=str + " ";
else
str=str + board[row][col];
Thank you.Hello all,
I am attempting to use the equals method with an
array and keep getting compiling errors. Could you
please take a look at my code and tell me where I am
going wrong:
if(board[row][col].equals(" "))
str=str + " ";
else
str=str + board[row][col];
Thank you.If you could post more of your code, that would be quite helpful... -
Hi, im trying to create a Phonebook class, I have succesfully added a method that finds the name and last name of the person entered by the user, however I cant seem to get my delete method working, the way how the delete method is supposed to work is that the user enters a name and lastname and then the array containing that number deletes the entry or else it displays an error message saying it hasnt been found.
this is what I have so far
Modify the program so that it can deal with an array that has null in some cells.
Now alter the program so that the user has a choice of three actions:
1. Search for a name (as above).
2. Add a new name and phone number to the array.
3. Delete a name (and phone number) from the array.
(Simple Method:) To delete a name and number from the array,
first find its cell, then assign null to that cell.
(The PhoneEntry previously referenced by that cell will be collected by the garbage collector.)
If the name to delete is not in the array, report an error.
(Better Method:) As it now stands, the program must deal with an array that might
have null values scattered throughout its cells. This is awkward and for a large array is
inefficient. A better notion is to keep the array organized so that all the nulls are together
at the end. Now when the array is searched, the first null signals the end of useful data and the search stops.
To delete a name and number from such an array, first find the name's cell.
If the name to delete is not in the array, report an error. Now copy the reference in the
last non-null cell to the deleted name's cell. Set the last non-null cell to to null.
Now the deleted PhoneEntry is garbage, and all the array still has all the nulls at the end.
class PhoneEntry
String firstname;
String lastname;
String phone;
PhoneEntry( String ln,String fn, String p )
lastname=ln;
firstname = fn;
phone = p;
class PhoneBook
PhoneEntry[] phoneBook;
final int ARRAY_LENGTH= 10;
PhoneBook() // constructor
phoneBook = new PhoneEntry[ARRAY_LENGTH] ;
phoneBook[0] = new PhoneEntry("Smith",
"John", "(418)665-1223");
phoneBook[1] = new PhoneEntry(
"Tony", "Gouidan", "(860)399-3044");
phoneBook[2] = new PhoneEntry(
"Jane", "Maryl", "(815)439-9271");
phoneBook[3] = new PhoneEntry(
"Babe","Jess", "(312)223-1937");
phoneBook[4] = new PhoneEntry(
"Wainstain" , "Emily", "(913)883-2874");
PhoneEntry search( String targetLName, String targetName)
boolean value= false;
for (int j=0; j< phoneBook.length-j-1; j++)
String lname= phoneBook[j].lastname.toUpperCase();
String fname= phoneBook[j].firstname.toUpperCase();
if ( targetLName.equals(lname) && targetName.equals("") )
System.out.println(phoneBook[j].lastname+" "+phoneBook[j].firstname+
" : "+phoneBook[j].phone);
value=true;
if ( targetName.equals(fname) && targetLName.equals("") )
System.out.println(phoneBook[j].lastname+" "+phoneBook[j].firstname+
" : "+phoneBook[j].phone);
value= true;
else if ( targetLName.equals(lname) && targetName.equals(fname) )
value= true;
int index=j;
return phoneBook[j];
if (value==false)
System.out.println("Name not found");
return null;
PhoneEntry add(String targetLName,String targetName, String number)
boolean value = false;
for (int j=0; j< phoneBook.length-1; j++)
if (phoneBook[j]==null)
value= true;
phoneBook[j] = new PhoneEntry (targetLName,targetName, number);
System.out.println("New number added in phoneBook ["+j+"]");
return phoneBook[j];
if (value==false)
System.out.println("No space available");
return null;
//THIS IS WHERE IM HAVING TROUBLE, THE THING IS THAT I DONT EVEN KNOW HOW TO START THE METHOD, SOME ORIENTATION OR HELP WILL BE HELPFUL
PhoneBook delete()
TESTER PROGRAM
class Tester
public static void main (String[] args)
EasyReader console= new EasyReader();
PhoneBook pb = new PhoneBook();
System.out.println("1-Find phone number 2-Add entry 3-Delete entry? (type 1,2 or 3 only)");
String answer= console.readLine();
if (answer.equals("1"))
System.out.println("Last Name? ");
String lname= console.readLine().toUpperCase();
System.out.println("Name? ");
String fname= console.readLine().toUpperCase();
PhoneEntry entry = pb.search(lname, fname);
if ( lname.equals("QUIT") || fname.equals("QUIT") )
System.out.println( "Good-bye." );
if ( entry != null)
System.out.println( entry.lastname +" "+entry.firstname +":"+ entry.phone);
else if (answer.equals("2"))
PhoneBook new_entry = new PhoneBook();
System.out.println("Enter last name: ");
String lastname= console.readLine();
System.out.println("Enter name: ");
String name = console.readLine();
System.out.println("Enter phone number: ");
String number = console.readLine();
PhoneEntry entered= new_entry.add(lastname, name, number);
if ( entered != null)
System.out.println( "New number added = "+entered.lastname +
" "+entered.firstname +":"+ entered.phone);
THIS IS WHERE I WANT THE DELETE METHOD TO TAKE EFFECT
else if (answer.equals("3"))
PhoneBook todelete = new PhoneBook();
System.out.println("Enter lastname to be deleted");
String del_lastname = console.readLine();
System.out.println("Enter name to be deleted");
String del_name = console.readLine();
String empty="";
//NOT SURE HOW TO MAKE IT HAPPEN THOUGH
PhoneEntry del_entry =pb.search(del_lastname, del_name);
System.out.println(del_last.firstname+" "+del_name.lastname+" has been deleted");
help will be greatly appreciated
thank youThis question has little to do with algorithms (this is the algorithms forum). I suggest you post your question in the general Java programming forum:
[http://forum.java.sun.com/forum.jspa?forumID=31]
Good luck. -
ToString() and equals() HELP!
Hi, this is my prompt:
Create an abstract class named Vacation that contains data fields (instance variables)
; a string variable; destination and a double variable; budget. Use an overloaded constructor, to allow client to set beginning values for destination and budget. That means the constructor takes two parameters, and calls two mutator methods one allowing the client to set new destination value for the vacation, and the next one to allow the client to set the new budget for the vacation. Furthermore this class contains accessor methods, one for returning the name of the destination of the vacation, and the other for returning the budget of the vacation. The class also holds two more methods, one is a toString( ), to return a string representation of the vacation, and an equals( ) method to compare two Vacation objects for the same vacation field value. Finally, the class has an abstract method that computes how much the vacation is over or under budget. That means returning by how much the vacation is over or under budget.
I've got this so far:
public abstract class Vacation
public String destination;
public double budget;
public Vacation()
destination = "";
budget = 0;
public Vacation(String destination, double budget)
this.destination = destination;
this.budget = budget;
public String getDestination()
return destination;
public void setDestination(String destination)
this.destination = destination;
public double getBudget()
return budget;
public void setBudget(double budget)
this.budget = budget;
public String toString()
return destination;
}could anyone tell me how to write a toString()/equals() method?Is this correct??? the original code is on the first
post...
also, i'm not sure if my toString() has all the
return values. I'm kind of confused by the wording of
the instructions and I don't know what a "string
representation of a vacation" quite means.It means whatever you want it to mean. You've decided it means the value of the destination field. You did the same in your attempt at overriding the equals method from the Object class, so you're consistent (that's good). But the equals method has the signature public boolean equals(Object o), the parameter type is Object, not String - so you'll need to change that and cast the parameter to be of type String (if that's what you really want - but I would think you'd want to be comparing Vacation objects, not String objects for equality). And I would think (but it's completely up to you) that you'd work the "budget" field's value into these methods somewhere (as suggested in a previous post) but again, it's completely up to you - I think that once you change the equals method signature you'll have satisfied the letter of the requirements.
public boolean equals(String
destination)
if(this.destination.equals(destination))
return true;
else
return false;
code] -
Difference between Object equals() method and ==
Hi,
Any one help me to clarify my confusion.
stud s=new stud();
stud s1=new stud();
System.out.println("Equals======>"+s.equals(s1));
System.out.println("== --------->"+(s==s1));
Result:
Equals ======> false
== ------------> false
Can you please explain what is the difference between equals method in Object class and == operator.
In which situation we use Object equals() method and == operator.
Regards,
Saravanan.Kcorlettk wrote:
I'm not sure, but I suspect that the later Java compilers might actually generate the same byte code for both versions, i.e. I suspect the compiler has gotten smart enough to devine that && other!=null is a no-op and ignore it... Please could could someone who understands bytecode confirm or repudiate my guess?Don't need deep understanding of bytecode
Without !=null
C:>javap -v SomeClass
Compiled from "SomeClass.java"
class SomeClass extends java.lang.Object
SourceFile: "SomeClass.java"
minor version: 0
major version: 49
Constant pool:
const #1 = Method #4.#15; // java/lang/Object."<init>":()V
const #2 = class #16; // SomeClass
const #3 = Field #2.#17; // SomeClass.field:Ljava/lang/Object;
const #4 = class #18; // java/lang/Object
const #5 = Asciz field;
const #6 = Asciz Ljava/lang/Object;;
const #7 = Asciz <init>;
const #8 = Asciz ()V;
const #9 = Asciz Code;
const #10 = Asciz LineNumberTable;
const #11 = Asciz equals;
const #12 = Asciz (Ljava/lang/Object;)Z;
const #13 = Asciz SourceFile;
const #14 = Asciz SomeClass.java;
const #15 = NameAndType #7:#8;// "<init>":()V
const #16 = Asciz SomeClass;
const #17 = NameAndType #5:#6;// field:Ljava/lang/Object;
const #18 = Asciz java/lang/Object;
SomeClass();
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 1: 0
public boolean equals(java.lang.Object);
Code:
Stack=2, Locals=2, Args_size=2
0: aload_1
1: instanceof #2; //class SomeClass
4: ifeq 25
7: aload_1
8: checkcast #2; //class SomeClass
11: getfield #3; //Field field:Ljava/lang/Object;
14: aload_0
15: getfield #3; //Field field:Ljava/lang/Object;
18: if_acmpne 25
21: iconst_1
22: goto 26
25: iconst_0
26: ireturn
LineNumberTable:
line 6: 0
}With !=null
C:>javap -v SomeClass
Compiled from "SomeClass.java"
class SomeClass extends java.lang.Object
SourceFile: "SomeClass.java"
minor version: 0
major version: 49
Constant pool:
const #1 = Method #4.#15; // java/lang/Object."<init>":()V
const #2 = class #16; // SomeClass
const #3 = Field #2.#17; // SomeClass.field:Ljava/lang/Object;
const #4 = class #18; // java/lang/Object
const #5 = Asciz field;
const #6 = Asciz Ljava/lang/Object;;
const #7 = Asciz <init>;
const #8 = Asciz ()V;
const #9 = Asciz Code;
const #10 = Asciz LineNumberTable;
const #11 = Asciz equals;
const #12 = Asciz (Ljava/lang/Object;)Z;
const #13 = Asciz SourceFile;
const #14 = Asciz SomeClass.java;
const #15 = NameAndType #7:#8;// "<init>":()V
const #16 = Asciz SomeClass;
const #17 = NameAndType #5:#6;// field:Ljava/lang/Object;
const #18 = Asciz java/lang/Object;
SomeClass();
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 1: 0
public boolean equals(java.lang.Object);
Code:
Stack=2, Locals=2, Args_size=2
0: aload_1
1: instanceof #2; //class SomeClass
4: ifeq 29
7: aload_1
8: ifnull 29
11: aload_1
12: checkcast #2; //class SomeClass
15: getfield #3; //Field field:Ljava/lang/Object;
18: aload_0
19: getfield #3; //Field field:Ljava/lang/Object;
22: if_acmpne 29
25: iconst_1
26: goto 30
29: iconst_0
30: ireturn
LineNumberTable:
line 6: 0
} -
What is hash code in Java and how it is related to equals method
Can any body give me the detailed information about hashcode and the relationship between equals method and hash code.
Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
int hashCode = SomeObject.hashCode();
The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
1. // Compare objects and then compare their hash codes
2. if (object1.equals(object2)
3. System.out.println("hash code 1 = " + object1.hashCode() +
4. ", hashcode 2 = " + object2.hashCode());
5.
6. // Compare hash codes and then compare objects
7. if (object1.hashCode() == object2.hashCode())
8. {
9. if (object1.equals(object2))
10. System.out.println"object1 equals object2");
11. else
12. System.out.println"object1 does not equal object2");
13. }
In lines 3-4, the value of the two hash codes will always be the same. However, the program may go through line 10 or line 12 in the code. Just because an object's reference equals another object's reference (remember that the equals() method compares object references by default), it does not necessarily mean that the hash codes also match.
The hashCode() method may be overridden by subclasses. Overriding the hash code will allow you to associate your own hash key with the object.
Maybe you are looking for
-
Hexadecimal Reading does not match the reading of RealTerm Serial Capture
Hi I am reading the output of a serial device that spits out hexadecimal characters. When I read its serial output with the VISA read block (using a string display with HexDisplay option on) I am getting hexadecimal characters. However, when I read
-
Usb to 232 converter and windows 7
Hi All, Taking a long shot hoping someone has an idea on what the possible solution could be. Hoping I've just missed something obvious. I have a customer who is using the NI usb to 232 converter. The software he is using is emh camcal software. He s
-
SMTP auth to relay server?
I want my server to relay mail through "smtp.comcast.net", but you have to have a name/pass to use it. server admin only gives me the option to put in the server not a password or anything. so any mail i send gets bounced as it should, i guess, witho
-
OC-genie not working as i expected after bios update
Hey guys, I have an P55-GD65 with an i7 860. It ran stable with oc genie on 3.55Ghz but after an bios update ocgenie only clocks to 2.98Ghz. Whats wrong, or what did i do wrong? Greetings.
-
in preparing to erase and reinstall for another problem I'm having, I backed up my mail libraries for 2004 and 2005.....january 2006 was still on .mac (IMAP); since they were on the server, I did not back them up; when I reloaded OX X and opened Mail