Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDerek Derek
8,744 PointsHelp with overriding compareTo()
Hello,
I am trying to override compareTo() by lastNames (String). However, for some reason, I can't get it to work and keep getting NullPointException at line 15 of Information.java, which I think is caused by the compareTo() method in Contact.java.
Below are the files, Contact.java and Information.java respectively.
I would really appreciate if you could help me fix compareTo() in Contact.java. It is identical to Craig's, different only in variable names.
Thank you in advance!
public class Contact implements Comparable {
private String mFirstName;
private String mLastName;
public Contact (String firstName, String lastName) {
mFirstName = mFirstName;
mLastName = mLastName;
}
public String getFirstName() {
return mFirstName;
}
public String getLastName() {
return mLastName;
}
public String getContact() {
return mFirstName + " " + mLastName;
}
@Override
public String toString() {
return "["+getContact()+"]";
}
@Override
public int compareTo(Object obj) {
Contact other = (Contact) obj;
if (equals(other)) {
return 0;
}
int compareLastNames = mLastName.compareTo(other.mLastName);
if (compareLastNames == 0) {
return mLastName.compareTo(other.mLastName);
}
return compareLastNames;
}
}
import java.util.Arrays;
public class Information {
public static void main(String[] args) {
Contact contact = new Contact("First1", "Last1");
Contact secondContact = new Contact("First2", "Last2");
System.out.println("This is name1: " + contact);
System.out.println("This is name2: " + secondContact);
Contact[] storage = {contact, secondContact};
System.out.println("This is the original storage: " + storage);
Arrays.sort(storage);
for (Contact name : storage) {
System.out.println(name);
}
}
}
2 Answers
Kourosh Raeen
23,733 PointsYou're getting the error because you're not setting the member fields correctly in the Contact constructor. It should look like this:
public Contact (String firstName, String lastName) {
mFirstName = firstName;
mLastName = lastName;
}
coskun olcucu
5,340 Pointswhat I see in your compareTo method that after equlas method ,you are supposed to compare fileds first name and last name,however,in your code you repeat comparing to first names.
Derek Derek
8,744 PointsDerek Derek
8,744 PointsWow, I can't believe I made that mistake and did catch it. Thank you!