Results 1 to 3 of 3
  1. #1
    Hollywood is offline Member
    Join Date
    Jan 2008
    Rep Power

    Default Help w/ generics

    I am not to sure if this works. It compiles just fine but is this the correct way to use generics?

    The assignment says "Write a generic method numberOf that takes an element and a list and returns the number of times the element appears in the list. Note the element may be of different type than the type of the entries in the list."

    Java Code:
    package listUtilities;
    import utilities.containers.*;
    public class ListUtil<E extends Comparable>{
       * Returns the number of times a generic element appears in the list. 
      public static <E> int numberOf(E element, List<? extends Comparable> list){
        int n = 0;
        for(int i = 0;i<list.size();i++){
          if ((list.get(i).getClass()).equals(element.getClass()) //check class equality
                &&list.get(i).compareTo(element)==0) //check value equality
            n++;//increment counter
        return n;
      }//end of numberOf
    }//end of class ListUtil

  2. #2
    CaptainMorgan's Avatar
    CaptainMorgan is offline Moderator
    Join Date
    Dec 2007
    NewEngland, US
    Rep Power

    Default this the correct way to use generics?
    I'm not sure about your logic as I haven't examined it thoroughly, so I don't know if it will return the correct values. But your use of Generics looks syntactically correct... someone correct me if I'm wrong.
    Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
    Want to voice your opinion on your IDE/Editor of choice? Vote now!
    Got a little Capt'n in you? (drink responsibly)

  3. #3
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    New York
    Rep Power


    This looks like fine to me. You've got the syntax right as far as i know.

Similar Threads

  1. Generics
    By sireesha in forum New To Java
    Replies: 2
    Last Post: 01-11-2008, 12:08 AM
  2. Generics
    By eva in forum New To Java
    Replies: 2
    Last Post: 01-04-2008, 10:10 PM
  3. Java confused over Generics?
    By Bibendum in forum New To Java
    Replies: 3
    Last Post: 12-26-2007, 07:23 AM
  4. Java Generics (an introduction)
    By Java Tutorial in forum Java Tutorial
    Replies: 0
    Last Post: 11-27-2007, 07:50 PM
  5. ArrayList<type> - Generics
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-14-2007, 04:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts