Contents

  1. ./AutoboxFixed.java
  2. ./AutoboxInt.java
  3. ./Autobox.java
  4. ./Card.java
  5. ./Deck.java
  6. ./IntegerListExample.java
  7. ./ListIteratorExamples.java
  8. ./MapExample.java

./AutoboxFixed.java 1/8

[
top][prev][next]
/**
 * This class fixes the autoboxing inefficiency from Autobox.java
 * 
 * @author Sara Sprenkle
 */
public class AutoboxFixed {

	/**
	 * Called when user runs java AutoboxFixed
	 */
	public static void main(String[] args) {
	    long startTime = System.currentTimeMillis();

	    long sum = 0L;
	    for (long i = 0; i < Integer.MAX_VALUE; i++) {
		sum += i;
	    }
	    System.out.println(sum);

	    long finishTime = System.currentTimeMillis();
	    double seconds = (finishTime - startTime)/1000.0;
	    System.out.println("Elapsed time: " + seconds + " s");
	}
}

./AutoboxInt.java 2/8

[
top][prev][next]
/**
 * This class demonstrates inefficiencies with unnecessary autoboxing.
 * Note that changing the loop's counter variable to an int does *not*
 * help with respect to improving runtime because the autoboxing is
 * still occuring. 
 * 
 * @author Sara Sprenkle
 */
public class AutoboxInt {

	public static void main(String[] args) {

		// Find the inefficiency in the code below.

		long startTime = System.currentTimeMillis();
		Long sum = 0L;
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}
		System.out.println(sum);
		
		long finishTime = System.currentTimeMillis();
		double seconds = (finishTime - startTime)/1000.0;
		System.out.println("Elapsed time: " + seconds + " s");
	}
}

./Autobox.java 3/8

[
top][prev][next]
/**
 * This class demonstrates inefficiencies with unnecessary autoboxing
 * 
 * @author Sara Sprenkle
 */
public class Autobox {

	public static void main(String[] args) {

		// Find the inefficiency in the code below.

		long startTime = System.currentTimeMillis();
		Long sum = 0L;
		for (long i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}
		System.out.println(sum);
		
		long finishTime = System.currentTimeMillis();
		double seconds = (finishTime - startTime)/1000.0;
		System.out.println("Elapsed time: " + seconds + " s");
	}
}

./Card.java 4/8

[
top][prev][next]
/**
 * Represents a playing card. Demonstrates use of enumerated types,
 * enum.  enums are not covered in class.  This class is here for use
 * in the Deck class and if you're curious about enums.
 *
 * @author Sara Sprenkle
 */
public class Card {

	/**
	 * Represents the ranks in a deck of playing cards
	 */
	public enum Rank {
		DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE;
	}

	/**
	 * Represents the suits in a deck of playing cards
	 */
	public enum Suit {
		CLUBS, DIAMONDS, HEARTS, SPADES;
	}

	// a card won't change its rank or suit after it is created
	private final Rank rank;
	private final Suit suit;

	/**
	 * Creates a new card object, with the given rank and suit
	 * 
	 * @param rank
	 * @param suit
	 */
	public Card(Rank rank, Suit suit) {
		this.rank = rank;
		this.suit = suit;
	}

	/**
	 * Returns this card's rank
	 * 
	 * @return card's rank
	 */
	public Rank getRank() {
		return rank;
	}

	/**
	 * Returns this card's suit
	 * 
	 * @return card's suit
	 */
	public Suit getSuit() {
		return suit;
	}

	/**
	 * 10, J, Q, K: 10 points A: 15 points all others: 5 points
	 * 
	 * @return the value of the card in the game of Rummy
	 */
	public int getRummyValue() {
		switch( rank ) {
		case ACE:
			return 15;
		case TEN:
		case JACK:
		case QUEEN:
		case KING:
			return 10;
		default:
			return 5;
		}
	}

	/**
	 * Determines if this card and another card have the same suit. Returns true
	 * if they do.
	 * 
	 * @param c
	 *            another Card to compare
	 * @return true iff the cards have the same suit
	 */
	public boolean sameSuit(Card c) {
		return this.suit.equals(c.suit);
		// return this.suit == c.suit;
		// return this.suit().equals(c.suit());
	}

	/**
	 * Returns a string representation of this card.
	 * 
	 * @return string representation of a Card in the form &lt;rank&gt; of
	 *         &lt;suit&gt;
	 */
	@Override
	public String toString() {
		// leverages toString() methods of Rank and Suit
		return rank + " of " + suit;
	}

	public static void main(String args[]) {
		Card jackOfDiamonds = new Card(Rank.JACK, Suit.DIAMONDS);
		Card aceOfDiamonds = new Card(Rank.ACE, Suit.DIAMONDS);
		System.out.println(jackOfDiamonds);

		if (jackOfDiamonds.sameSuit(aceOfDiamonds)) {
			System.out.println(jackOfDiamonds + " and " + aceOfDiamonds
					+ " are the same suit.");
		}
		System.out.println("The rummyValue of " + jackOfDiamonds + " is "
				+ jackOfDiamonds.getRummyValue());
	}
}

./Deck.java 5/8

[
top][prev][next]
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Represents a deck of playing cards
 * 
 * @author Sara Sprenkle
 */
public class Deck {

    // define our instance variable as an *interface* variable, List, not the
    // concrete implementation class.

    // Only Card objects can be put into the list or taken
    // out of the list.
    /** a list of Card objects */
    private List<Card> deck;
    
    /**
     * Creates a new, shuffled deck of cards
     */
    public Deck() {
        this(true);	
    }
    
    /**
     * Creates a new deck of cards
     * 
     * @param shuffle
     *            - true if the cards should be shuffled
     */
    public Deck(boolean shuffle) {
        deck = new ArrayList<>();
        refresh(shuffle);
    }
    
    /**
     * Refresh the deck from the beginning -- as in, it contains all the cards again
     * 
     * @param shuffle true if the cards should be shuffled
     */
    public void refresh(boolean shuffle) {
        // removes all the Cards from the deck
        deck.clear();
        
        // Use the enums defined in the Card class
        for (Card.Suit suit : Card.Suit.values()) {
            for (Card.Rank rank : Card.Rank.values()) {
                Card c = new Card(rank, suit);
                deck.add(c);
            }
        }
        
        if (shuffle) {
            shuffle();
        }
    }

    /**
     * Display the contents of the deck.
     */
    public void display() {
        for (Card c : deck) {
            System.out.println(c);
        }
    }

    /**
     * Shuffles the deck of cards
     */
    public void shuffle() {
        Collections.shuffle(deck);
    }
    
    /**
     * Draws the first/"top" card from the deck, removes it from the deck, 
     * and returns the chosen card
     * 
     * @return the top card from the deck, which is removed
     */
    public Card draw() {
        return deck.remove(0);
    }

    /**
     * Returns a list of cards of size numCards that are drawn
     * from the top of the deck.
     * 
     * @param numCards the number of cards to deal
     * @return a list of cards (of the specified size)
     */
    public List<Card> deal(int numCards) {
        /* Note that this method returns a *List*, not an 
        ArrayList.  This adds flexibility to our code.
        We can change the list implementation (maybe a 
        LinkedList would be better?) and the calling code
        is not affected.
        */
        List<Card> hand = new ArrayList<>();
        for (int i = 0; i < numCards; i++) {
            hand.add(draw());
        }
        return hand;
    }
    
    /**
     * Evaluates the strength of a hand in Poker, poorly.
     * Returns an integer representing the strength of the hand.
     * @param pokerHand a poker hand
     * @return the strength of the hand in poker
     */
    public static int calcStrengthOfHand(List<Card> pokerHand) {
        int strength = 0;
        for( Card c : pokerHand ) {
            if( c.getRank() == Card.Rank.ACE ) {
                strength += 5;
            } else {
               strength += 1;
            }
        }
        return strength;
    }        


    /**
     * Demo some functionality of the Deck class.
     *
     * @param args not used in this method
     */
    public static void main(String[] args) {
        Deck d = new Deck();
        d.display();
        d.shuffle();
        
        /* deal returns a List<Card>.  I don't know which List
        implementation is used, and I don't *need* to know.  
        If the Deck's underlying implementation changes, 
        my code doesn't need to change!  Horray!!
        */
        List<Card> myHand = d.deal(5);
        System.out.println("\nMy hand contains:");
        for( Card c : myHand ) {
            System.out.println(c);
        }
        
        System.out.println("\nMy hand's strength in Poker is " + calcStrengthOfHand(myHand));
    }
}

./IntegerListExample.java 6/8

[
top][prev][next]
import java.util.*;

/**
 * Making a List of random numbers of length 100 than of a random
 * size, to show dynamic sizing.  Comparing time required to generate
 * the list with creating an array, each of length 100.
 * 
 * @author Sara Sprenkle
 */
public class IntegerListExample {

	public static void main(String[] args) {

	    Random rand = new Random();

	    // List size: 100
	    long startTime = System.currentTimeMillis();
	    List<Integer> myList = new ArrayList<>();
	    
	    for( int i=0; i < 100; i++ ) {
	        myList.add(rand.nextInt(100));
	    }
	    
	    System.out.println("My list of random numbers of length " + myList.size() + ":");
	    for( int i : myList ) {
	        System.out.println(i);
	    }

	    long endTime = System.currentTimeMillis();
	    
	    myList.clear();

	    	    
	    double secondsForList = (endTime - startTime)/1000.0;

	    System.out.println("Generating list again but with a random size, to show benefit of List!");
	    
	    for( int i=0; i < rand.nextInt(1,100); i++ ) {
	        myList.add(rand.nextInt(100));
	    }
	    
	    System.out.println("My list of random numbers of length " + myList.size() + ":");
	    for( int  i :myList ) {
	        System.out.println(i);
	    }

	    startTime = System.currentTimeMillis();

	    int[] myArray = new int[100];
	    for( int i=0; i < 100; i++ ) {
	        myArray[i] = rand.nextInt(100);
	    }

	    System.out.println("\nMy array of random numbers of length " + myArray.length + ":");
	    for( int i : myArray ) {
	        System.out.println(i);
	    }

	    endTime = System.currentTimeMillis();
	    double secondsForArray = (endTime - startTime)/1000.0;


	    // Compare the time required for primitive types with arrays rather than Objects.
	    System.out.println("\n\nComparing time required to create 100 random numbers using List vs array.");

	    System.out.println("List creation took " + secondsForList + " seconds");
	    System.out.println("Array creation took " + secondsForArray + " seconds");
	    
	}
}

./ListIteratorExamples.java 7/8

[
top][prev][next]
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Random;

/**
 * Examples of using List Iterators
 * 
 * @author CSCI209
 */
public class ListIteratorExamples {

	/**
	 * Condition (we are using this for the items that we want to keep in our
	 * list).
	 * 
	 * @param value the value to consider
	 * @return true if the value is evenly divisible by 2
	 */
	public static boolean condition(int value) {
		return value % 2 == 0;
	}

	/**
	 * Display the given list, starting with the header.
	 *
	 * @param myList the list to be displayed
	 * @param header the header to display the list
	 */
	private static void displayList(List<Integer> myList, String header) {
		System.out.println(header);
		for (Integer i : myList) {
			System.out.println(i);
		}
	}

	public static void main(String[] args) {
	    
	    Random numberGenerator = new Random();

		// set up a list
		List<Integer> myList = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			myList.add(numberGenerator.nextInt());
		}

		displayList(myList, "Original List:");
		System.out.println();

		Iterator<Integer> iter = myList.iterator();

		while (iter.hasNext()) {
			Integer item = iter.next();
			if (!condition(item)) {
				// alternatively, could mutate this object, if the object has
				// mutator methods available.
				// Can't replace this item or remove the item and add in a new
				// object.
				iter.remove();
			}
		}

		displayList(myList, "Next List:");
		
		ListIterator<Integer> iter2 = myList.listIterator(myList.size());
		int counter = myList.size();
		while( iter2.hasPrevious() ) {
		    iter2.previous();
		    if( counter % 2 == 0 ) {
		        iter2.add(counter);
		    }
		    counter--;
		}
		
		System.out.println();
		displayList(myList, "Final List:");

	}

}

./MapExample.java 8/8

[
top][prev][next]
import java.util.HashMap;
import java.util.Map;

/**
 * A few examples of maps, based on command-line arguments.
 * Usage:
 *      java MapExample cat dog
 *      java MapExample cat dog cat cat dog
 * 
 * @author Sara Sprenkle
 *
 */
public class MapExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	    // State the key's type and the value's type
		Map<String, Integer> argToLength = new HashMap<>();

		for (String arg : args) {
			// if there are duplicate arguments, this will write over the previous entry in the map.
			argToLength.put(arg, arg.length());
		}
		
		// display the results
		System.out.println("Arguments' Lengths: ");
		for( String arg : argToLength.keySet() ) {
			System.out.println(arg + " --> " + argToLength.get(arg));
		}
		
		System.out.println("\n");
		
		// ------- Another Example --------
		// count the arguments
		Map<String, Integer> argToCount = new HashMap<>();
		
		for (String arg : args) {
			// if there are duplicate arguments, this will write over that entry in the map.
			if( argToCount.containsKey(arg) ) {
			    int oldCount = argToCount.get(arg);
			    // showing using put and getting the old value back
			    int oldValue = argToCount.put(arg, oldCount + 1);
			    System.out.println("The old value for " + arg + " was " + oldValue);
			} else {
			    argToCount.put(arg, 1);   
			}
		}
		
		// display the results
		System.out.println("\nArguments' Number of Occurrences: ");
		for( String arg : argToLength.keySet() ) {
			System.out.println(arg + " --> " + argToCount.get(arg));
		}

	}

}

Generated by GNU Enscript 1.6.5.90.