CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann
Michael Eckmann - Skidmore College - CS Fall 2008 Todays Topics More Java Review Comments about the programming assignment We'll write code using an ArrayList of Cards and sort them. While we're writing the code, please slow me down or just ask me to comment on why we're using a particular class or method or whatever. This is to be meant as a review
Michael Eckmann - Skidmore College - CS Fall 2008 Programming Assignment Storing the data –array drawback is have a maximum length and you need to keep track of current length, removing elements? –linked list variable length, but be careful when sorting because swapping two nodes needs care, easy to add and remove nodes –ArrayList variable length, but how would you sort them?
Michael Eckmann - Skidmore College - CS Fall 2008 Programming Assignment Storing the data –ArrayList variable length, but how would you sort them? your data class could implements Comparable interface and then use the compareTo method on two objects to determine if they need to be swapped use add (2 versions), get, set, remove methods
Michael Eckmann - Skidmore College - CS Fall 2008 Programming Examples Let's create a Card class to represent a playing card –add an equals methods –add a compareTo method Create a class that stores a Deck of Cards –store them in an ArrayList –write a simple insertion sort method to sort them
Michael Eckmann - Skidmore College - CS Fall 2008 equals public boolean equals(Object o) { if (o instanceof Card) { Card c = (Card) o; return ((c.suit == this.suit) && (c.rank == this.rank)); } else return false; }
Michael Eckmann - Skidmore College - CS Fall 2008 equals Things to make sure you understand: –which Card is which --- One card calls equals (this) and one card is passed in as a parameter (o). –why can I refer to private suit and rank instance variables? –what is the purpose of the if (o instanceof Card) check? –Does it really return true if the cards are equal and false if they are not? How? –Why is an equals method necessary at all --- why not just use something like (c1 == c2) instead of (c1.equals(c2))? –This method overrides the equals method in Object so it had to have had the same signature what's a signature?