Commit adc1fc8a authored by Trisha Gee's avatar Trisha Gee
Browse files

[Ch10b] TreeSet with comparator

parent abe6fa85
Loading
Loading
Loading
Loading
+7 −1
Changes for src/main/java/ch10b/TestTree.java: 7 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -21,7 +21,7 @@ public class TestTree {
}

class Book implements Comparable<Book> {
  private String title;
  String title;
  public Book(String t) {
    title = t;
  }
@@ -29,4 +29,10 @@ class Book implements Comparable<Book> {
  public int compareTo(Book other) {
    return title.compareTo(other.title);
  }

  public String toString() {
    return "Book{" +
            "title='" + title + '\'' +
            '}';
  }
}
 No newline at end of file
+28 −0
Changes for src/main/java/ch10b/TestTreeComparator.java: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
package ch10b;

import java.util.Comparator;
import java.util.TreeSet;

public class TestTreeComparator {
  public static void main(String[] args) {
    new TestTreeComparator().go();
  }

  public void go() {
    Book b1 = new Book("How Cats Work");
    Book b2 = new Book("Remix your Body");
    Book b3 = new Book("Finding Emo");
    BookCompare bookCompare = new BookCompare();
    TreeSet<Book> tree = new TreeSet<>(bookCompare);
    tree.add(b1);
    tree.add(b2);
    tree.add(b3);
    System.out.println(tree);
  }
}

class BookCompare implements Comparator<Book> {
  public int compare(Book one, Book two) {
    return one.title.compareTo(two.title);
  }
}