Generic Methods Exercises

  < Previous  Next >

Vector

  1. Discuss with someone else the difference between ArrayList and Vector classes
  2. Declare a Vector object that stores the vowels in the English alphabet ('a', 'e', 'i', 'o', 'u' and 'y'). Display each of it's elements on a separate line.

Generic Methods

  1. Discuss with someone else an advantage of using generics
  2. Convert the following method to be a generic method:
    /**
     * Swap the elements at two indices
     * <p>Note: Does not check if the indices are valid</p>
     * @param array The array
     * @param index1 The index of one of the elements to swap
     * @param index2 The index of other element to swap
     */
    public static void swap2( Integer[] array, int index1, int index2 ){
        Integer temp = array[index1];
        array[ index1 ] = array[ index2 ];
        array[ index2 ] = temp;
    }
    
    public static void main( String[] args ){
        Integer[] nums = {1,2,3};
        Character[] hello = {'h', 'e', 'l', 'l', 'o'};
    
        for( int i : nums ){
            System.out.print( i );
        }
    
        swap2( nums, 1, 2 );
        for( int i : nums ){
            System.out.print( i );
        }
        System.out.println("\n");
    
        for( Character c : hello ){
            System.out.print( c );
        }
    
        swap2( hello, 1, 2 );
        for( Character c : hello ){
            System.out.print( c );
        }
        System.out.println("\n");
    }
  3. Does the following method compile? If not, why? source
    import java.util.List;
    
    /**	    
     * Display all of the numbers (whole or real) in a list on one line
     * @param lst A list of Numbers
     */
    public <T extends Number> void printList(List<T> lst) {
        for( Number n : lst )
            System.out.print(n + " ");
        System.out.println();
    }
  4. Write a generic method to match the following Javadoc. Additionally, add code to main() to call the method twice (each with a different type).
    /**
     * Finds the minimum value in a list between two indices
     * <p>Note: Does not check if the indices are valid</p>
     * @param lst The list object
     * @param startIndex The index to start looking at
     * @param endIndex The last index to consider
     * @return The smallest value in lst between startIndex and endIndex (inclusive) 
     */
    Note, "<" and ">" can only be used for primitives. However, any object that implements the Comparable< T > interface can call compareTo( T otherObj ).