EE408 Lab 2: Common Methods in Class java.lang.Object (toString() and equals()), Classes, Interfaces, and Subtyping


3%

Due: 5 PM, Friday September 5.

In a separate email, I sent you 6 Java files, Set.java, ArraySet.java, BinaryTreeSet.java, Greater.java, Main_String.java, and Main.java.
These files define the following classes and interfaces:
Save these files onto the local disk and do the following exercises.

1. Create an Eclipse project named sets and import these 6 classes into sets. Run Main_String.main() and Main.main() from within Eclipse.

2. (1%) Open up BinaryTreeSet.java in Eclipse and remove the phrase "implements Set" from the definition of the BinaryTreeSet class. What happens in the IDE and why?

3. (2%) Create a Point class with two coordinates x and y, both of type int.

public class Point {
private int x;
private int y;
public Point(int x, int y) ... // constructor
public int getX() ...
public int getY() ...
public String toString() ... // string concatenation to represent Point: "("+x+","+y+")"
public boolean equals(Object o) ... // need to test o is instance of Point; cast o to Point object-- Point p = (Point)o; then access x and y of p and compare them with x and y of this object
}

Write a class Main_Point and add a main() method into Main_Point.

Create a BinaryTreeSet object and assign it to a local variable of type Set. But to put Point objects into BinaryTreeSet, an object of type Greater must be passed as a parameter to the BinaryTreeSet constructor. BinaryTreeSet uses it to compare two Point objects.

Greater comp = new Greater(){
      public boolean gt(Object o1, Object o2){
           if (o1 instanceof Point && o2 instanceof Point){
              Point p1 = (Point)o1;
              Point p2 = (Point)o2;
              return p1.getX()>p2.getX() || (p1.getX()==p2.getX() && p1.getY()>p2.getY());
           }
          return false;
      }
  };

Alternative to an anonymous class, one could also create a class, let's say Comparator, which implements Greater:

public class Comparator implements Greater{
      public boolean gt(Object o1, Object o2){
           if (o1 instanceof Point && o2 instanceof Point){
              Point p1 = (Point)o1;
              Point p2 = (Point)o2;
              return p1.getX()>p2.getX() || (p1.getX()==p2.getX() && p1.getY()>p2.getY());
           }
          return false;
      }
  }

One can then initialize comp with an object of Comparator,

Greater comp = new Comparator();

Create two Point objects that represent point (0,0).

Insert both objects into the set object. Test the cardinality of the set. It should be 1.

Print out the set on the console. {(0,0)} should be the output.


Demonstrate to me once you are done with these exercises so that I can grade.