CSC300 Jan28

slide version

single file version

Contents

  1. Topics
  2. Equality
  3. Order Comparisons
  4. Constructors
  5. Constructors (continued)
  6. ArrayList (more details)
  7. Raw Type ArrayList (cont)
  8. Stack
  9. Iterator Interface
  10. Stack Application
  11. Stack Application 1 (hw4)
  12. 1.3.4 Details
  13. How to read input one character at a time
  14. Example
  15. Queue
  16. Queue Application
  17. 1.3.3
  18. 1.3.13
  19. 1.3.6
  20. 1.3.12

Topics[1] [top]

  1. Equality
  2. Order Comparisons
  3. Constructors
  4. ArrayList (more details)
  5. Generic classes
  6. Stack
  7. Interfaces
  8. Iterator Interface
  9. Stack Application
  10. Debugging in Eclipse
  11. Queue
  12. Queue Application
  13. 1.3.3
  14. 1.3.6
  15. 1.3.12
  16. 1.3.13

Equality[2] [top]

Warning Common mistake is to use the == operator to test class types for equality.

Note: Using == for class types will not generate a compile error, but it is WRONG! Using == just compares the addresses, not the values of class objects.

Example: basic types

Use == to test for equality for basic types.

    1	public static void main(String[] args)
    2	{
    3	  Scanner in = new Scanner(System.in);
    4	  int x, y;
    5	
    6	  x = in.nextInt();
    7	  y = in.nextInt();
    8	
    9	  if (x == y) {
   10	    System.out.printf("equal");
   11	  } else {
   12	    System.out.printf("not equal");
   13	  }
   14	}
Example: class types

Use the equals method to test for equality for class types.

    1	public static void main(String[] args)
    2	{
    3	  Scanner in = new Scanner(System.in);
    4	  String x, y;
    5	
    6	  x = in.next();
    7	  y = in.next();
    8	
    9	  if (x.equals(y)) {
   10	    System.out.printf("equal");
   11	  } else {
   12	    System.out.printf("not equal");
   13	  }
   14	}

Order Comparisons[3] [top]

Another common mistake is to use one of the relational operators <, >, etc to compare class types.

Unlike ==, the compiler will catch this error.

Basic types

Use the relational operators: <, <=, etc., to compare the order of basic types:

    1	public static void main(String[] args)
    2	{
    3	  Scanner in = new Scanner(System.in);
    4	  int x, y;
    5	
    6	  x = in.nextInt();
    7	  y = in.nextInt();
    8	
    9	  if (x < y) {
   10	    System.out.printf("max is " + y);
   11	  } else {
   12	    System.out.printf("max is " + x);
   13	  }
   14	}
Class types

Use the compareTo method to compare the order of class types. (Note that not all class types have this method.)

    1	public static void main(String[] args)
    2	{
    3	  Scanner in = new Scanner(System.in);
    4	  String x, y;
    5	
    6	  x = in.next();
    7	  y = in.next();
    8	
    9	  if (x.compareTo(y) < 0) {
   10	    System.out.printf("max is " + y);
   11	  } else {
   12	    System.out.printf("max is " + x);
   13	  }
   14	}

Here max means occurs later in the ordering of the class type.

      x.compareTo(y)   Meaning
        < 0         x comes before y in the ordering
        == 0           x is equal to y
        > 0         x comes after y in the ordering

    

Constructors[4] [top]

Does the IntPair class have a constructor?

    1	public class IntPair
    2	{
    3	  private int x;
    4	  private int y;
    5	
    6	  public IntPair(int x, int y)
    7	  {
    8	     this.x = x;
    9	     this.y = y;
   10	  }
   11	  
   12	  public IntPair()
   13	  {
   14	    x = 0;
   15	    y = 0;
   16	  }
   17	
   18	  public int x() {
   19	    return x;
   20	  }
   21	 
   22	  public int y() {
   23	    return y;
   24	  }
   25	}

Constructors (continued)[5] [top]

Does this class have a constructor?

    1	public class IntPair
    2	{
    3	  private int x;
    4	  private int y;
    5	
    6     public setX(int x) { this.x = x;}
    7
    8     public setY(int y) { this.y = y;}
    9	
   10 	  public int x() {
   11	    return x;
   12	  }
   13	 
   14	  public int y() {
   15	    return y;
   16	  }
   17	}

ArrayList (more details)[6] [top]

ArrayList is a generic class. This means that the type of the elements to be stored in the ArrayList is a parameter - a type parameter - to be specified when an ArrayList instance is declared.

      ArrayList<Integer> intArr = new ArrayList<Integer>();
      ArrayList<String> strArr; = new ArrayList<String>();
    

Common mistake (but unfortunately, only a compiler warning):

      ArrayList lst = new ArrayList();  // No type specified for elements.
    

Error at line 11: The operator + is undefined for types int and Object

    1	public class RawTypeApp {
    2	  public static void main(String[] args) {
    3	    ArrayList lst = new ArrayList();
    4	    for(int i = 0; i < 5; i++) {
    5	      lst.add(i);
    6	    }
    7	    
    8	    int sum = 0;
    9	    
   10	    for(int i = 0; i < lst.size(); i++) {
   11	      sum = sum + lst.get(i);  // what type is lst.get(i)
   12	    }
   13	    System.out.printf("sum = %d\n", sum);
   14	  }
   15	
   16	}

Raw Type ArrayList (cont)[7] [top]

The raw type can be used (and you had to do this before generics were added to Java)

    1	public class RawTypeApp {
    2	  public static void main(String[] args) {
    3	    ArrayList lst = new ArrayList();
    4	    for(int i = 0; i < 5; i++) {
    5	      lst.add(i);
    6	    }
    7	    
    8	    int sum = 0;
    9	    
   10	    for(int i = 0; i < lst.size(); i++) {
   11	      sum = sum + (int) lst.get(i);  // cast specifies the type
   12	    }
   13	    System.out.printf("sum = %d\n", sum);
   14	  }
   15	
   16	}

Stack[8] [top]

Stack<E>
(private members)
boolean empty()
void push(E x)
E pop()
E peek()
Iterator<E> iterator()

How could a Stack client (user of Stack) print the stack elements?

Can we do it without changing the Stack contents?

Iterator Interface[9] [top]


public interface Iterator&lt;E&gt;
{
   public boolean hasNext();
   public E next();
   public void remove(); // optional; i.e., can just throw an exception
}
Example
ArrayList<Integer> lst = new ArrayList<Integer>();
for(int i = 0; i < 10; i++) {
   lst.add(i);
}

Iterator<Integer> it = lst.iterator();

while(it.hasNext()) {
  System.out.println(it.next());
}

Stack Application[10] [top]

8 queens problem

In chess a queen controls the row, the column, and the diagonals that intersect the position of the queen on the 8 x 8 chess board (8 rows, 8 columns).

Although each side only has 1 queen in chess, the 8 queens puzzle is to place 8 queens on the 8 x 8 chess board so that each row, column and diagonal contains at most one queen.

A solution can be found by placing one queen in each row, one at a time avoiding the columns and diagonals controled by the previously placed queens.

The problem is that this process may come to a row where every entry is already controlled by a previously placed queen.

The algorithm must then backup to the previous row and choose a different square for the queen in that row and try again.

Stack Application 1 (hw4)[11] [top]

1.3.4 Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).

1.3.4 Details[12] [top]

1.3.4 Write a stack client Parentheses that reads in a text stream from standard input and uses a stack to determine whether its parentheses are properly balanced. For example, your program should print true for [()]{}{[()()]()} and false for [(]).

Adding word, etc., changes the solution to the problem only slightly.

That is, for input

      [(Hello) World!]{Is this balanced?}{[(one)(two)](three)}
    

the program should return true.

For input

      [(Is this ] balanced?)
    

the program should return false.

How to read input one character at a time[13] [top]

The Scanner class has a method:

      public Scanner useDelimiter(String pattern)
    

The default pattern matches any sequence of whitespace characters (blank ' ', tab '\t', newline '\n', carriage return '\r' and a few more)

So the next() method will skip leading string made up of the delimiter characters and stop at trailing delimiter characters or end of input.

Setting the delimter to the empty string causes the next() method to not skip any leading characters and it will read a string consisting of just one character.

Example[14] [top]

This simple example reads an input text file, in.txt, prints the file to standard output one character at a time and prints the total number of '(' characters and the total number of ')' characters.

    1		
    2	 public static main(String[] args) {
    3	   Scanner in = MyIO.openInput("in.txt");
    4	   in.useDelimiter("");
    5	   int lparenCount = 0;
    6	   int rparenCount = 0;
    7	
    8	   while(in.hasNext()) {
    9	     String s = in.next();
   10	     char ch = s.charAt(0); 
   11	     System.out.print(ch);
   12	     if (ch == '(' ) {
   13		lparenCount++;
   14	     } else if (ch == ')' ) {
   15		rparenCount++;
   16	     }
   17	   }
   18	   System.out.printf("\nThere were %d '(' and %d ')'\n",
   19	     lparenCount, rparenCount);
   20	 }

Queue[15] [top]

Queue<E>
(private members)
boolean empty()
void add(E x)
E remove()
E peek()
Iterator<E> iterator()

Queue Application[16] [top]

Write the static method readInts in a class MyIO. The method should have a file name as an argument and return an array of all the integers in the file. (That is, implement Sedgewick's readInt library method.)


public class MyIO
{

   public static int[] readInts(String fname)
   {
      ...
   }
}

1.3.3[17] [top]

1.3.3 Suppose that a client performs an intermixed sequence of (stack) push and pop operations. The push operations put the integers 0 through 9 in order onto the stack; the pop operations print out the return values. Which of the following sequence(s) could not occur?

a. 4 3 2 1 0 9 8 7 6 5
b. 4 6 8 7 5 3 2 9 0 1
c. 2 5 6 7 4 8 9 3 1 0
d. 4 3 2 1 0 5 6 7 8 9
e. 1 2 3 4 5 6 9 8 7 0
f. 0 4 6 5 3 8 1 7 2 9
g. 1 4 7 9 8 6 5 3 0 2
h. 2 1 4 3 6 5 8 7 9 0
    

1.3.13[18] [top]

1.3.13 Suppose that a client performs an intermixed sequence of (queue) enqueue and dequeue operations. The enqueue operations put the integers 0 through 9 in order onto the queue; the dequeue operations print out the return value. Which of the following sequence(s) could not occur?

a. 0 1 2 3 4 5 6 7 8 9
b. 4 6 8 7 5 3 2 9 0 1
c. 2 5 6 7 4 8 9 3 1 0
d. 4 3 2 1 0 5 6 7 8 9
    

1.3.6[19] [top]

1.3.6 What does the following code fragment do to the queue q?


Stack<String> stack = new Stack<String>();

while (!q.isEmpty()) {
  stack.push(q.dequeue());
}

while (!stack.isEmpty()) {
  q.enqueue(stack.pop());
}

For example, suppose the elements in the queue are:

(front) "A" "B" "C" "D" "E" (back)
    

1.3.12[20] [top]

1.3.12 Write an iterable Stack client that has a static method copy() that takes a stack of strings as argument and returns a copy of the stack. Note : This ability is a prime example of the value of having an iterator, because it allows development of such functionality without changing the basic API.