What else I must do allow my method to handle any type of objects

Posted by NewHelpNeeder on Stack Overflow See other posts from Stack Overflow or by NewHelpNeeder
Published on 2012-10-20T16:51:47Z Indexed on 2012/10/20 17:01 UTC
Read the original article Hit count: 140

Filed under:
|
|
|

So to allow any type object I must use generics in my code.

I have rewrote this method to do so, but then when I create an object, for example Milk, it won't let me pass it to my method.

Ether there's something wrong with my generic revision, or Milk object I created is not good.

How should I pass my object correctly and add it to linked list?

This is a method that causes error when I insert an item:

   public void insertFirst(T dd)  // insert at front of list
   {
      Link newLink = new Link(dd);   // make new link

      if( isEmpty() )                // if empty list,
         last = newLink;             // newLink <-- last
      else
         first.previous = newLink;   // newLink <-- old first
      newLink.next = first;          // newLink --> old first
      first = newLink;               // first --> newLink
   }

This is my class I try to insert into linked list:

class Milk
{
    String brand;
    double size;
    double price;

    Milk(String a, double b, double c)
    {
        brand = a;
        size = b;
        price = c;
    }
}

This is test method to insert the data:

   public static void main(String[] args)
      {                             // make a new list
      DoublyLinkedList theList = new DoublyLinkedList();

      // this causes:
      // The method insertFirst(Comparable) in the type DoublyLinkedList is not applicable for the arguments (Milk)
      theList.insertFirst(new Milk("brand", 1, 2));      // insert at front

      theList.displayForward();     // display list forward
      theList.displayBackward();    // display list backward
      }  // end main()
   }  // end class DoublyLinkedApp

Declarations:

class Link<T extends Comparable<T>>
   {}

class DoublyLinkedList<T extends Comparable<T>>
   {}

© Stack Overflow or respective owner

Related posts about java

Related posts about generics