Jump to content

A few questions about comparable and generics

- - - - -

  • Please log in to reply
8 replies to this topic

#1
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
Here is the code so you can see I am doing the work before my questions.

/**

 * Program: LabTwoA

 *

 * Note:

 *    The methods commented out all do the same thing and work

 *    To verify just comment out the far left comment markers for the 

 *    block of code you want to see.

 *    

 *    

 *

 * Formula used:

 * @author Mr Mike S.

 */

public class LabTwoA {


    //----------------------------------------------------------------//

    //                       FIRST PROBLEM                            //

    //----------------------------------------------------------------//


    /**

     * A method used to print an array of objects

     * @param object any type

     */

 /*   public static void printArray(Object [] object){

        for(int i = 0; i < object.length; i++){

            System.out.print(object[i] + " ");

        }// end of for loop

        System.out.println();// space after list is printed

    }// end of printArray(Object [] object)


    //-----------------------------------------------------------------//

    //                  EXERCISE TWO                                   //

    //-----------------------------------------------------------------//


    /**

     * Prints an array of integers

     * @param integer

     */

/*    public static void printArray(Integer[] integer ){

        for(int i = 0; i < integer.length; i++){

            System.out.print(integer[i] + " ");

        }// end of for loop

        System.out.println();// space

    }// end of printArray(Integer)


    /**

     * Prints an array of doubles

     * @param doubArray

     */

/*    public static void printArray(Double [] doubArray ){

        for(int i = 0; i < doubArray.length; i++){

            System.out.print(doubArray[i] + " ");

        }

        System.out.println();

    }// end of printArray(Double)


    /**

     * Prints an array of Characters

     * @param character

     */

/*    public static void printArray(Character [] character ){

        for(int i = 0; i < character.length; i++){

            System.out.print(character[i] + " ");

        }

        System.out.println();

    }// end of printArrray(Character)


    /**

     * Prints an array of Strings

     * @param strArray

     */

/*    public static void printArray(String [] strArray ){

        for(int i = 0; i < strArray.length; i++){

            System.out.print(strArray[i] + " ");

        }

        System.out.println();

    }// end of printArray(String)


    //------------------------------------------------------------------//

    //              EXCERSISE THREE                                     //

    //------------------------------------------------------------------//


 *

 */

    /**

     * Generic method used to print values of an array

     * @param <Values> Integers, Double, Character, String, etc.

     * @param anyArray any array value

     */

    public static <Values> void printArray(Values[] anyArray){

        for(Values values : anyArray){

            System.out.print(values + " ");

        }

        System.out.println("\n");

    }// end of generic method


    //----------------------------------------------------------------//

    //                     EXCERSISE FOUR                             //

    //----------------------------------------------------------------//


    /**

     * This method will find the max value in array

     * @param a

     * @return

     */

    public static Comparable getMax(Comparable [] a){

        

    }

    /**

     * Main method

     * @param arrrgs command line argument

     */

    public static void main(String [] arrrgs){

        Integer[] intArray = {2, 3, 4, 5, 6};

        Double[] doubleArray = {2.3, 3.4, 4.5, 5.6, 6.7};

        Character[] charArray = {'H', 'E', 'L', 'L', 'O'};

        String[] strArray = {"one", "two", "buckle", "your", "shoe"};


        System.out.println("The intArray produces this list:");

        printArray(intArray);

        System.out.println("The doubleArray produces this list:");

        printArray(doubleArray);

        System.out.println("The charArray produces this list:");

        printArray(charArray);

        System.out.println("The strArray produces this list:");

        printArray(strArray);

    }// end of main method


}// end of LabTwo class


Here are my questions:
1. Will the array have to be sorted before getting compared using compareTo method?
2. Can someone give me an example using Generics for the below method with
comments a "dumbed dow version"? Please try to find an alternate way to show me without answer handed to me.
3. Not related question: What is the function object technique?


 /**

     * This method will find the max value in array

     * @param a

     * @return

     */

    public static Comparable getMax(Comparable [] a){

       // body ...... return .....

    }


Thanks to all in advance.
Good answers will definitely get +rep

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
  • Shouldn't have to, just go through the array of Comparables and check each one against the previous largest value.
  •  /**
    
         * This method will find the max value in array
    
         * @param a List of comparables to return max value.
    
         * @return
    
         */
    
        public static Comparable getMax(Comparable [] a){
    
           // This method isn't using Generics, so I'll perform the proper coercion.
    
           return getMax(new Vector<Comparable>(a));
    
        }
    
    
        public static <T extends Comparable> T getMax(Iterable<T> collection)
    
        {
    
            // If the collection is null, throw NullPointerException.
    
            if (collection == null) throw new NullPointerException();
    
    
            // We're going to iterate through the collection
    
            Iterator<T> iter = collection.iterator();
    
            T largestSoFar = null;
    
    
            while (largestSoFar == null)
    
            {
    
                // It's possible for any element to be null, and we need to make sure if it
    
                // is null to skip it, unless there's no more elements in the list, then break.
    
                // Serendipitously, this also handles the case of there being no elements.
    
    
                if (!iter.hasNext()) break;
    
                largestSoFar = iter.next();
    
            }
    
        
    
            while (iter.hasNext())
    
            {
    
                //This is the loop you'd want to use compareTo in. Also, you're going to want to
    
                // have a second reference of type T to compare from, and check if it's larger. If
    
                // it is, you need to replace largestSoFar with next.
    
                // Don't forget to check for null!
    
            }
    
    
            return largestSoFar;
    
        }
    I didn't test this code, but I think it should work.
  • Using comparators is a good example of the Function Object Technique. On Wikipedia

Wow I changed my sig!

#3
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
Thanks for the help.

2. Will arraylists work the same way as this.
return getMax(new Vector<Comparable>(a));

3. I should have realized this with the assignments I have.

Thanks again for the help
+rep

#4
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
Yes, ArrayLists should work just as well as Vector, all that was required was that the object passed was an Iterable that iterates over a list of objects that extend Comparable.
Wow I changed my sig!

#5
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
This is the code I turned in. I ignored checking for a null set, but understand for a bigger program it is needed; Thanks for the tip.
One more question...for now.
Is the same code used in my implementation

   public static <T extends Comparable<T>> T getMax(T[] a) {

        T biggestValue = a[0];

        // use compareTo max position

        for (int i = 0; i < a.length; i++) {

            if (a[i].compareTo(biggestValue) > 0) {

                biggestValue = a[i];

            }// end of if

        }// end of for


        return biggestValue;

    }

what you intended me to put in these instructions?


while (iter.hasNext())

        {

            //This is the loop you'd want to use compareTo in. Also, you're going to want to

            // have a second reference of type T to compare from, and check if it's larger. If

            // it is, you need to replace largestSoFar with next.

            // Don't forget to check for null!

        }


Thanks again

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I hope i don't have to make a new Thread for my question.
Even though I understand how to program with generics. Take this simple method:
public <T extends MyInterface> void doSomething(T object){

   object.methodFromInterface();

}
This kind of code will/should work fine if you have the interface and pass an object which implements that interface to the method.
But now my question:
Why would you choose to do it "the Generics way" instead of simply using only interface declarations, and let Java up- and downcast.
Like:

public void doSomething(MyInterface object){

   object.methodFromInterface();

}

Both will work (I think) but the interfaces make much more sence.
I DO understand that you want to use generics, if you use the type T multiple times in the method declaration,
(Because otherwise you could still be using 2 different classes as long as they both have the interface, with generics it must be 2 of the same class with that interface)

but if its return type is "void" and only 1 parameter is of unknown type T.. Is there a reason for generics then?.

#7
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
@wim_DC: As you probably know, Generics are ultimately just hiding a system of object class casting that the compiler can be certain is safe. For your particular method, there's no reason to use Generics at all. And for any method
public <T extends MyInterface> void doSomething(T object)
there's probably no reason to use Generics. The only reason you'd want to use generics when you're taking one argument of unknown type T that I can think of is if you want T to extend multiple interfaces for some reason:
public <T extends MyInterface & MyFriendsInterface> void doSomething(T object)
Or, of course, when the interface you're using is, in itself, Generic (such as Comparable).
Wow I changed my sig!

#8
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
good

#9
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
@mr mike: I forgot to answer your question I just realized. :P

Essentially, yes, what you have in your code is what you should have written, simply using iterators instead of array dereferencing.
Wow I changed my sig!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users