java object comparisons
play

Java Object Comparisons Mason Vail, Boise State University Computer - PowerPoint PPT Presentation

Java Object Comparisons Mason Vail, Boise State University Computer Science What Does Equal Mean? Same Object? or Equivalent Objects? Comparing references vs. Comparing objects obj1 == obj2 Compares references to see if they are


  1. Java Object Comparisons Mason Vail, Boise State University Computer Science

  2. What Does “Equal” Mean? Same Object? or Equivalent Objects?

  3. Comparing references vs. Comparing objects obj1 == obj2 Compares references to see if they are aliases: the same object in memory. obj1.equals(obj2) Compares two objects for equivalence, if equals() has been overridden. If not overridden, equals() has the same result as == .

  4. Comparable: Defining Natural Order Natural Order - the most common or obvious ordering. Integers: 1 3 3 4 6 9 11 12 12 12 15 Comparable interface defines natural order via int compareTo() int result = obj1.compareTo(obj2) -value : obj1 comes before obj2 0 : obj1 and obj2 are equivalent - .equals() should be true +value : obj2 comes before obj1

  5. Comparable Contact Class //constructor, accessors, mutators not shown public class Contact implements Comparable<Contact> { private String lastName, firstName; private long phoneNumber; public int compareTo(Contact other) { int result = this.lastName.compareTo(other.lastName); if (result == 0) { result = this.firstName.compareTo(other.firstName); } return result; } public boolean equals(Contact other) { return (this.lastName.equals(other.lastName) && this.firstName.equals(other.firstName)); } }

  6. Comparator: Alternate Ordering For ordering other than by natural order (or for classes that did not implement Comparable ), the Comparator interface defines a similar compare() method. Comparator reverseComparator = new ReverseComparator(); int result = reverseComparator.compare(obj1, obj2); -value : obj1 comes before obj2 0 : obj1 and obj2 are equivalent - .equals() should be true +value : obj2 comes before obj1

  7. Comparator for Contact Class /** orders Contacts in reverse order by last name, first name */ public class ReverseComparator implements Comparator<Contact> { public int compare(Contact c1, Contact c2) { int result = -(c1.getLastName().compareTo(c2.getLastName())); if (result == 0) { result = -(c1.getFirstName().compareTo(c2.getFirstName())); } return result; } }

  8. Java Object Comparisons Mason Vail, Boise State University Computer Science

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend