Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: Generics

  1. #1
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Generics

    So I'm completely stumped..

    this is the goal:
    1. Start a new class named GenericStack that specifies a type variable that provides for generics.
    2. Declare a linked list that will hold the elements in the stack, then use the linked list to implement the methods shown above (which is push(),pop(),peek(),size().


    And this is all I got so far and need help:
    import java.util.LinkedList;
    import java.util.Scanner;
    public class GenericStack<E>
    {
        private LinkedList<E> list = new LinkedList<E>();
     
        public void push(E item) //the parameter is an item of type E
        {
             //list is our linked list, put the new item at the end
            list.add(item);
        }
        public void pop(E item)
        {
          list.remove();
       }
       public void peek(E item)
       {
          list.peek();
       }
       public int size(E item)
       {
          return list.size();
     
       }
    }

    and then:
    public class GenericStackApp
    {
     
        public static void main (String args[])
        {
         {
     
     
               //lets make our stack be a stack of Strings
               GenericStack<String> stack = new GenericStack<String>();
     
               //and push a String on it
               stack.push("A String");
     
               int size = stack.size();
               System.out.println(size);
        }
        }
     
     
    }
    Last edited by helloworld922; December 5th, 2010 at 04:38 PM.


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Generics

    So your problem is what?

  3. #3
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    Lol, I can't figure out how to get it to send me back the size or in fact, I can't figure out ANY of the peek(),pop(),size()...

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Generics

    I've never implemented a stack before, but ill give it my best shot.

    public int size(E item)
       {
          return list.size();
     
       }

    that should be

    public int size()
       {
          return list.size();
     
       }

    and your pop method should remove a specific object not just remove();

  5. #5
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    That worked like a charm! thank you!


    :::EDIT:::
    How do I use the peek() then?
    Last edited by _lithium_; December 5th, 2010 at 05:17 PM.

  6. #6
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Generics

    No problem, sorry i can't help you further

  7. #7
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    Any idea on how to configure peek()?

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Generics

    What's wrong with using the Stack class?

    Java API: Stack (Java 2 Platform SE v1.4.2)

    That aside, if you want a peek method, simply return the item at the top of stack without removing it.
       public E peek(E item)
       {
          return list.getFirst();
       }

  9. #9
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    Since I am supposed to be able to find the index number of the item, I know I need to use the indexOf() but can't figure out how to implement it into my app.
    	public int index(E item)
    	{
    		return list.indexOf(item);
    	}
    Take 'item' as the parameter from the app but whenever I try to pass something to it from my GenericStackApp.java, it just keeps show -1.
    Last edited by _lithium_; December 6th, 2010 at 02:06 PM.

  10. #10
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    EDIT:::

    Got it, I'm dumb and forgot the -1 indicates that the value wasn't found. Forgot to place the index call after the push().
    Last edited by _lithium_; December 6th, 2010 at 02:26 PM.

  11. #11
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    Well, hop through the list
    public int index (E item)
    {
    for (int i =0; i < size(); i++)
    {
    if (list.get(i).equals(item))
    return i;
    }
    return -1;
    }

    However, beware, as if E doesn't have an equals method, it may use Object's or something like that and only return an index if they share the same memory location.

    However, that's the best I can come up with at the moment.

    However, there is a huge problem with such a method.

    A Stack usually only cares what's on top.

    It's not usually supposed to know what's in the rest of the list.
    Last edited by javapenguin; December 6th, 2010 at 02:36 PM.

  12. The Following User Says Thank You to javapenguin For This Useful Post:

    _lithium_ (December 6th, 2010)

  13. #12
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    Well I've been trying to get the get() method working but keep getting errors with the:
    	public int get(E item)
    	{
    		return list.get(item);
    	}

    I can't figure out how to basically get the index number.

  14. #13
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    The LinkedList class already has a get(int index) method.

    But again, a Stack usually is only concerned with get(0).

    The get method returns a variable of type E.

    If, using the for loop I gave earlier, you check if list.get(int index) and it equals it then it has it.

    Warning: this will return the first occurrence of something. If you are looking for the value 1 and have a 1 at index 3 and at index 7, it will return 3.

    Also, if that class doesn't override Object's equals, it will only return an index if they have the same reference in memory.

  15. #14
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    import java.util.*;
     
    public class GenericStack<E>
    {
        private LinkedList<E> list = new LinkedList<E>();
     
        public void push(E item) //the parameter is an item of type E
        {
             //list is our linked list, put the new item at the end
            list.add(item);
        }
        public boolean pop(E item)
        {
    		return list.remove(item);
    	}
    	public E peek()
    	{
    		return list.getLast();
    	}
    	public int size()
    	{
    		return list.size();
     
    	}
    	public int index(E item)
    	{
    		return list.indexOf(item);
    	}
    	public int get(E item)
    	{
    		return list.get(item);
    	}
    }
    public class GenericStackApp
    {
     
        public static void main (String args[])
        {
    	  {
    		    int index;
    		    index = 0;
    			DeedsHeading.getHeading("Assignment 1, Parts 3 & 4");
    	        //lets make our stack be a stack of Strings
    	        GenericStack<String> stack = new GenericStack<String>();
     
    	        //and push a String on it
    	        System.out.print("  Pushing 8 items onto the GenericStack.\n");
    	        System.out.print("  Index   Item\n");
    	        //push/index
    	        stack.push("Oranges");
    	        index = stack.index("Oranges");
    			System.out.print("    " + index);
    	        System.out.print("\t  Oranges\n");
    	        stack.push("Apples");
    	        index = stack.index("Apples");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Apples\n");
    	        stack.push("Bananas");
    	        index = stack.index("Bananas");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Bananas\n");
    	        stack.push("Strawberry");
    	        index = stack.index("Strawberry");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Strawberry\n");
    	        stack.push("Basil");
    	        index = stack.index("Basil");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Basil\n");
    	        stack.push("Oregano");
    	        index = stack.index("Oregano");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Oregano\n");
    	        stack.push("Pepper");
    	        index = stack.index("Pepper");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Pepper\n");
    	        stack.push("Garlic");
    	        index = stack.index("Garlic");
    	        System.out.print("    " + index);
    	        System.out.print("\t  Garlic\n\n");
     
     
    	        System.out.print("  The stack now contains " + stack.size() + " items\n\n");
    	        System.out.print("  The most recent entry was \"" + stack.peek() + "\"\n\n");
     
    	        //Remove 5 items
    	        System.out.print("  Removing five items from the stack\n");
    	        stack.pop("Garlic");
    	        System.out.print("  Pop:  Garlic\n");
    	        stack.pop("Pepper");
    	        System.out.print("  Pop:  Pepper\n");
    	        stack.pop("Oregano");
    	        System.out.print("  Pop:  Oregano\n");
    	        stack.pop("Basil");
    	        System.out.print("  Pop:  Basil\n");
    	        stack.pop("Strawberry");
    	        System.out.print("  Pop:  Strawberry\n");
     
    	        //What is left
    	        System.out.print("\nThe stack still contains " + stack.size() + " item(s)\n");
    	        stack.get(0);
        }
        }
     
     
    }


    This is what I have so far. (thought it'd make it easier if I added my code for reference =/)

  16. #15
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    list.get(item) is invalid.

    List.contains(item)
    is valid

    list.get(int index) is valid.

    If you want the index, do a for loop and check for all the indexes to see if

    item = list.get(index);

  17. #16
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    Besides, if you're trying to get the item itself, your return type would be type E.

    Also, maybe this is just to show what it is, but I can't find this variable/class

    DeedsHeading.getHeading("Assignment 1, Parts 3 & 4");

  18. #17
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    For instance, if you want to get the top, usually the only place a Stack can get to,
    you'd be this:

    public E top()
    {
    return list.getFirst();
    }

    if you want to get an item at an index, you'd do this

    public E item(int index)
    {
    return list.get(index);
    }

    I know of no method that will get the item outright.

    Anyway, if you already have a method to get the index of the item.

    You could do this to see if the item is there

    public boolean containsItem(E item)
    {
    if (list.contains(item))
    return true;
    else
    return false;
    }

    Also, list.get(item)

    is invalid.

    First, the get method of LinkedList takes an int, not a generic parameter as a parameter.

    Second, get returns an generic variable, not an int variable.

    You simply cannot have a method

    public int getItem(E item)
    {
    return list.get(item);
    }

  19. #18
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

     
    import java.util.*;
     
    public class GenericStack<E>
    {
        private LinkedList<E> list = new LinkedList<E>();
     
        public void push(E item) //the parameter is an item of type E
        {
             //list is our linked list, put the new item at the end
            list.add(item);
    // most stacks only put new item at beginning.  Just saying.
     
        }
        public void pop(E item)
        {
    if (!list.contains(item))
    return;
        // their remove method is boolean as theirs returns true if the list contains the item.
    // yours doesn't so it just should remove the item...er...provided that the item is there in the first place
           list.remove(item);
        }
        public E peek()
        {
            return list.getLast();
        }
        public int size()
        {
            return list.size();
     
        }
        public int index(E item)
        {
            return list.indexOf(item);
        }
     
        public E get(int index)
        {
            return list.get(index);
        }
     
    }

    Here's how most stack classes are
    public class GenericStack<E>
    {
        private LinkedList<E> list = new LinkedList<E>();
     
        public void push(E item) //the parameter is an item of type E
        {
             //list is our linked list, put the new item at the end
            list.addFirst(item);
    // most stacks only put new item at beginning.  Just saying.
     
        }
        public void pop()
        {
    if (list.size() ==0)
    return;
        // their remove method is boolean as theirs returns true if the list contains the item.
    // yours doesn't so it just should remove the item...er...provided that the item is there in the first place
           list.removeFirst();
        }
     
        public int size()
        {
            return list.size();
     
        }
      public E top()
    {
    return list.getFirst();
    }
     
     
    }

  20. #19
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    The main final task is to display what is left in the LinkedList, I'm just struggling to find an easy solution without actually just programming it into the code to say the actual ones that I know are left....

  21. #20
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    Well, add a method called toString() to your generic stack class.

    public String toString()
    {
    return list.toString();
    }

    then later, in your main class, you can

    stack.toString() to show a list of remaining items.

  22. #21
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Generics

    Yeah I thought of doing that but then the issue is, he wants the index number to be displayed correspondingly. I got the get() working, so I can just For loop it and run up the index number to the corresponding item i think.

  23. #22
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Generics

    The best part, I think, is that your index number, say your list
    has
    [5, 3, 2, 1, 9]

    left would be

    index 0 = 5;
    index 1 = 3;
    index 2 =2;
    index 3 = 1;
    index 4 = 9;

Similar Threads

  1. Generics collections and reflection
    By juza in forum Collections and Generics
    Replies: 2
    Last Post: November 30th, 2010, 02:14 AM
  2. Help, Want to make a BASIC min value Method with Generics
    By Iglesias in forum Collections and Generics
    Replies: 6
    Last Post: September 12th, 2010, 10:16 PM
  3. Trying to somehow Compare Generics
    By Omega_ryan in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 14th, 2010, 12:58 PM
  4. Generics and Reflection
    By Kassiuz in forum Collections and Generics
    Replies: 3
    Last Post: March 15th, 2010, 09:32 AM
  5. Implementing Multiple Interfaces with Generics
    By darkestfright in forum Collections and Generics
    Replies: 5
    Last Post: February 10th, 2010, 07:44 PM