Contents

  1. ./AutoboxFixed.java
  2. ./Autobox.java
  3. ./Card.java
  4. ./Deck.java
  5. ./FindDuplicates2.java
  6. ./FindDuplicates3.java
  7. ./FindDuplicates.java
  8. ./ListIteratorExamples.java
  9. ./MapExample.java

./AutoboxFixed.java 1/9

[
top][prev][next]
/**
 * This class demonstrates fixing the autoboxing inefficiency.
 * 
 * @author Sara Sprenkle
 */
public class AutoboxFixed {

	/**
	 * Called when user runs java 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");
	}
}

./Autobox.java 2/9

[
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 3/9

[
top][prev][next]
/**
 * Represents a playing card. Demonstrates use of enumerated types, enum.
 * enums are not covered in class.  This class is mostly here for use in the
 * Deck class and if you're curious about enums.
 *
 * @author CSCI209
 */
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 rank() {
		return rank;
	}

	/**
	 * Returns this card's suit
	 * 
	 * @return card's suit
	 */
	public Suit suit() {
		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 4/9

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

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

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

    // Note that 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
     * @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;
    }

    /**
     * @param args
     */
    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 isn't used, and I don't *need* to know. 
        If the 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);
        }
    }
}

./FindDuplicates2.java 5/9

[
top][prev][next]
import java.util.HashSet;
import java.util.Set;

/**
 * From the array of command-line arguments, identify the duplicates.
 * 
 * 
 * 
 * @author CSCI209 Class
 * 
 */
public class FindDuplicates2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	    
	    System.out.println("This program finds the duplicates in the command-line arguments.");
		
	    Set<String> nonDuplicates = new HashSet<>();
	    
	    for( String string : args ) {
            if( nonDuplicates.contains(string) ) {
                System.out.println("found duplicate " + string); 
            } else{
                nonDuplicates.add(string);   
            }
	    }
	}

}

./FindDuplicates3.java 6/9

[
top][prev][next]
import java.util.HashSet;
import java.util.Set;

/**
 * From the array of command-line arguments, identify the duplicates.
 * 
 * Solution leverages the add method, which returns a boolean value--
 * true if that element was not already in the set (so the element was 
 * added to the set) or false if it was already in the set.
 * 
 * @author CSCI209 Class
 * 
 */
public class FindDuplicates3 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
	    System.out.println("This program finds the duplicates in the command-line arguments.");
	     
	    Set<String> nonDuplicates = new HashSet<>();
	    
	    for( String string : args ) {
            if( ! nonDuplicates.add(string) ) {
                System.out.println("found duplicate " + string); 
            }
	    }

	}

}

./FindDuplicates.java 7/9

[
top][prev][next]
import java.util.HashSet;
import java.util.Set;

/**
 * From the array of command-line arguments, identify the duplicates
 * 
 * @author CSCI209 Class
 * 
 */
public class FindDuplicates {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
	    System.out.println("This program finds the duplicates in the command-line arguments.");
	}

}

./ListIteratorExamples.java 8/9

[
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 9/9

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

/**
 * Trivial example of using a map.
 * Maps the argument to the length of the argument
 * 
 * @author CSCI209
 *
 */
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 that 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));
		}

	}

}

Generated by GNU Enscript 1.6.5.90.