Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.

Slides:



Advertisements
Similar presentations
Generics, Lists, Interfaces
Advertisements

ACM/JETT Workshop - August 4-5, Classes, Objects, Equality and Cloning.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Effective Java, Chapter 3: Methods Common to All Objects.
Java Software Solutions
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
Comparable and Comparator Nuts and Bolts. 2 Nuts and bolts Four methods underlie many of Java’s important Collection types: equals, compare and compareTo,
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Subclasses. Inheritance class Animal { int row, column; // will be inherited private Model model; // private prevents inheritance Animal( ) {... } //
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Introduction to Searching and Sorting
Static Class Members Wrapper Classes Autoboxing Unboxing.
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Stacks, Queues, and Deques
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Java versus C# An introduction to C# and Visual Studio.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS2110 Recitation Week 8. Hashing Hashing: An implementation of a set. It provides O(1) expected time for set operations Set operations Make the set empty.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Programming in Java (COP 2250) Lecture 8 Chengyong Yang Fall, 2005.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Section 4 Boxing classes Boxing classes Array initialization Array initialization Lists: recursion and iteration Lists: recursion and iteration.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Symbol Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Java Type System and Object Model Horstmann ch , 7.7.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Relations.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
COMP 110 Some notes on inheritance, review Luv Kohli December 1, 2008 MWF 2-2:50 pm Sitterson 014.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
1 CS1110 Classes, wrapper classes, Vectors. 10 Feb 2012 Miscellaneous points about classes. Discussion of wrapper classes and class Vector Use the text.
More on Objects Static and equals.. Each object takes memory Each time you make an object of a given class – you create a space in memory. E.g. public.
Searching.
COMP 110 Some notes on inheritance, review
Introduction to Searching and Sorting
CSE 1030: Implementing Non-Static Features
Searching.
Review for Midterm 3.
Presentation transcript:

Comparing Objects in Java

The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value were a Person, but it is not-- the value of p is a reference to a Person –The actual data for this Person is stored elsewhere –The value actually in p is a 4-byte pointer to this data When we do assignment, p2 = p, or comparison, p2 == p, we are working with the pointer values When we use dot notation, p.name, we dereference the pointer to get to the actual data values The comparison p == p2 does not test if the data are equal; it tests if the pointers are equal

Searching an array of Objects What does it mean to search for an object? –Are you looking for that identical object? If so, == is what you need –Or are you looking for any object that is “equal” according to some other criterion? There are many possible criteria—same name field or id field, all data equal, all elements the same but possibly in a different order, etc. You can use the equals method to search an array of Objects, provided –The operation equals has been defined appropriately equals has been defined for Strings to have the expected meaning –There is also an equalsIgnoreCase method for Strings For almost all other objects, the default meaning of equals is ==

Templates In Java you cannot write a search method that works for any type of array To do this, you would need a template facility—a way to write methods that can take parameters of any type –C++ has templates –Templates are likely to be added to a future version of Java Note, however: –We can write a method that works for Object s (because Object has equals defined, even if it just means == ) –Such a method would also work fine for String s (because the String class overrides equals ) We can wrap primitives and put them in an array of Objects

Type wrappers For every primitive type, there is a corresponding wrapper class, in java.lang, to easily make an Object from the primitive: –booleanBoolean –byteByte –charCharacter –doubleDouble –floatFloat –intInteger –longLong –shortShort Here is an example: class Integer { private int value; // Constructor Integer(int v) { value = v; } public int intValue() { return value; } } There’s more to the Integer class than this, but this is the most important part

Java review: equals The Object class defines public boolean equals(Object obj) For most objects, this just tests identity: whether the two objects are really one and the same This is not generally what you want The String class overrides this method with a method that is more appropriate for Strings The wrapper classes for primitive types also override equals appropriately You can override equals for your own classes –Just write your own equals, defined exactly as above –But there are some rules you should follow if you do

Overriding equals If you override equals, your method should have the following properties (for your objects x, y, z ) –Reflexive: for any x, x.equals(x) should return true –Symmetric: for any non-null objects x and y, x.equals(y) should return the same result as y.equals(x) –Transitive: if x.equals(y) and y.equals(z) are true, then x.equals(z) should also be true –Consistent: x.equals(y) should always return the same answer (unless you modify x or y, of course) –For any non-null x, x.equals(null) should return false Java cannot check to make sure you follow these rules

About sorted arrays When we just say an array is “sorted,” by default we mean that it is sorted in ascending order: smaller elements come first There is no notion of “smaller” for elements of the Object class, hence: –An array of Object cannot be in sorted order ! –But we can define an ordering for objects that belong to a class we define If we ensure that our array of Objects holds only objects for which we have defined an ordering, then we can sort that array –In addition to equals, we need some notion of “larger” and “smaller”

The Comparable interface java.lang provides a Comparable interface with the following method: –public int compareTo(Object that) –This method should return: A negative integer if this is less than that Zero if this equals that A positive integer if this is greater than that You implement an interface like this: class MyObject implements Comparable { public int compareTo(Object that) {...}...other stuff... }

Rules for implementing Comparable You must ensure: –x.compareTo(y) and y.compareTo(x) either are both zero, or else one is positive and the other is negative –x.compareTo(y) throws an exception if and only if y.compareTo(x) throws an exception –The relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0 –if x.compareTo(y)==0, then x.compareTo(z) has the same sign as y.compareTo(z) You should ensure: – compareTo is consistent with equals

Consistency with equals compareTo is consistent with equals if: x.compareTo(y)==0 gives the same boolean result as x.equals(y ) Therefore: if you implement Comparable, you really should override equals as well Java doesn’t actually require consistency with equals, but sooner or later you’ll get into trouble if you don’t meet this condition

The End