Chapter 21- Using Generics

package csu.matos;

import java.util.ArrayList;

public class Driver {

/**

* Author: Matos

* Date: July-18-2011

* Goal: Using Generics. Contrasting a hand-made integer holding stack with a

* more general-purpose hand-made generic stack

*

*/

public static void main(String[] args) {

try {

// using int stack

IntStack istk = new IntStack(10);

istk.push(111);

istk.push(222);

istk.push(333);

while(istk.top > -1){

int value = istk.pop();

System.out.println(value);

}

// using a generic stack

GenStack<Integer> gstk = new GenStack<Integer>();

gstk.push(1111);

gstk.push(2222);

gstk.push(3333);

while(gstk.data.size()> 0){

int value = gstk.pop();

System.out.println(value);

}

// using the generic stack

GenStack<String> gstk2 = new GenStack<String>();

gstk2.push("aaa");

gstk2.push("bbb");

gstk2.push("ccc");

while(gstk2.data.size()> 0){

String value2 = gstk2.pop();

System.out.println(value2);

}

// demo binary search on generic list

String[] lst = {"aaa", "bbb", "ccc", "ddd", "eee", "fff"};

int position = binarySearch(lst, "b2");

System.out.println("Binary: " + position);

} catch (Exception e) {

System.out.println("PROBLEMS: " + e.getMessage());

}

}//main

public static <E extends Comparable<E>

int binarySearch(E[] list, E key){

int low = 0;

int high = list.length - 1;

int mid;

while (low <= high){

mid = (low + high)/2;

if (key.compareTo(list[mid])==0)

return mid;

else if (key.compareTo(list[mid]) < 0)

high = mid -1;

else

low = mid + 1;

}

return -low - 1;

}

}

package csu.matos;

public class IntStack {

int[] data;

int top;

public IntStack(int capacity) {

data = new int[capacity];

top = -1;

}

public void push(int value) throws Exception{

try {

data[++top] = value;

} catch (Exception e) {

throw new Exception("Stack - Overflow error");

}

}//push

public int pop() throws Exception{

if (top >= 0)

return data[top--];

else

throw new Exception("Stack underflow error");

}

}

package csu.matos;

import java.util.ArrayList;

public class GenStack<E> {

ArrayList<E> data;

public GenStack(){

data = new ArrayList<E>();

}

public void push(E item){

data.add(0,item);

}

public E pop() throws Exception{

try {

return data.remove(0);

} catch (Exception e) {

throw new Exception("ERROR - underflow");

}

}

}