Implementing Iterable interface

Just trying to implement the the Iterable<> interface into my Stack class ... as far as I can tell I cannot specify a type beyond Object when iterating through it using the ForEach loop structure. Any thoughts on how to correct this or is my design limited?
* @(#)Queue.java
* @Matthew Cox
* @version 1.00 2009/2/11
import java.util.*;
public class Stack<T> implements Iterable<T>
     private LinkedList<T> list;
     private int size;
    public Stack()
         list = new LinkedList<T>();
         size = 0;
    public void push(T node)
         if (node != null)
              list.addFirst(node);
              size++;
         else
              System.out.println("Cannot push null value onto stack.");
    public T pop()
         T removedNode = null;
         if (!isEmpty())
              removedNode = list.removeFirst();
         else
              System.out.println("Stack is empty.");
         return(removedNode);
    public T[] toArray()
         return((T[]) list.toArray());
    public boolean isEmpty()
         return(size == 0);
    public boolean equals(LinkedList vList)
         return(list.equals(vList));
    public Iterator<T> iterator()
         return(list.iterator());
    public static void main(String[] args)
         Stack s1 = new Stack<Integer>();
         for (int count=0; count< 10; count++)
              s1.push(new Integer(count)); //(int)(Math.random()*16+0)
         for(Object i : s1) //RIGHT HERE, I want to be able to say "Integer i : s1" but I get an incompatible types error
              System.out.println(i);
}I don't really understand why I would be getting the error stating the the type being sent back is Object ... my Iterator() method returns an iterator of type T not type Object from how I understood it... any thoughts?

// Stack  s1 = new Stack<Integer>(); // this loses the type information
Stack <Integer> s1 = new Stack<Integer>();

Similar Messages

  • Iterator interface, how to implement?

    Hi,
    I'm working on an assignment, but I can't really understand one thing. In the following few lines I'll try to describe the situation.
    I have a class which has a TreeMap of Objects. These Objects have there own variables etc... and are comparable.
    Now I need to implement an interface which makes it possible to iterate over the objects in the TreeMap.
    And I need to add some functions like:
    getCurrent() (where does the pointer stands at this moment)
    getNbElements() (how many elements are there after the current position of the pointer)
    advance() (put the pointer one position further, like next() but without the return)
    reset() (put the pointer back at the first element)
    I have no idea how to implement this, do I need to create a seperate class which is the iterator ?
    I hope someone can clear some things up, I don't need a solution, just a way of thinking.
    Thanks in advance.

    Shyamisuga wrote:
    S. U can do all tat by implementing method for each of ur function., instead my suggestion would be to use Arraylist in this case, as they hav all these functions implemented, u just gotto cal them, makes life lot simpler.. :)Awesome advice. He can implement them by implementing them. I thank the gods you're not a pathologist
    "Lassa fever? Ah, that's easy to cure. Simply cure it, and it'll be cured"

  • Iterator Interface.A question please.

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    Now we are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body???
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    Thanks Will.
    Regarding the question,then why define an Iterator interface when
    the collection class implements the functionality?
    Why not define the methods hasNext() and next() in the Object
    class?
    So by default,all classes extends the Object class ,we
    cud use the hasNext() and next() method?
    No??? Or am I wrong?

  • Iterator Interface.A question please......respond

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    Now we are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body???
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    Thanks for yr reply.
    So you mean to say the the Iterator methods hasNext()
    and next()
    are being implemented by the Vector class.right?Not exactly. The Vector class defines an inner class, and it is this class that implements the Iterator interface, and so these two methods. When you write code like
    Vector myVector = new Vector();
    // code to fill myVector...
    Iterator it = myVector.iterator();the call to the iterator() method tells myVector to give you an instance of this inner class. The Vector class itself doesn't implement next() or hasNext().
    Then why define an interface with these methods at
    all?
    Why not give concrete bodies to these methods and put
    them in
    the Object Class.If you did that, then all classes would inherit them - all classes would be iterators. That wouldn't make sense, though, as clearly not all classes are meant to be used to iterate over collections of objects.
    Iterator is an interface so that a consistent API can be defined for iteration. As iterators are used in lots of different places, it is very helpful to have all of them guaranteed to have next() and hasNext() methods (amongst others). It is also very helpful to be able to call the iterator() method on any Collection class and know that the object that is returned, regardless of its implementation, will be of type Iterator.
    Then we can call them polymorphically.???But that's what you're doing - Vector and ArrayList (for example) have different implementations of Iterator, but code that iterates over them doesn't need to know that. As both return objects that implement the Iterator interface, they are interchangeable; that's polymorphism at work.

  • Iterator Interface. A question?

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    We are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body?.
    Arent they supposed to be empty()?
    If they have no body,then how are they being implemented?
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    public Iterator iterator()
    Returns an iterator over the elements in this list in proper sequence.
    This implementation returns a straightforward implementation of the iterator interface, relying on the backing list's size(), get(int), and remove(int) methods.
    Note that the iterator returned by this method will throw an UnsupportedOperationException in response to its remove method unless the list's remove(int) method is overridden.
    This implementation can be made to throw runtime exceptions in the face of concurrent modification, as described in the specification for the (protected) modCount field.
    Specified by:
    iterator in interface List
    Specified by:
    iterator in class AbstractCollection
    Returns:
    an iterator over the elements in this list in proper sequence.
    See Also:
    modCount
    So based on the above JavaDoc for java.util.AbstractList, which Vector sub-classes, the iterator() method returns an implementaion of the iterator interface. This is where the methods are defined.

  • How to implement XI interfaces in online and offline modes?

    Hi Everybody,
    Can you please tell me how to implement XI interfaces in online and offline modes?
    thanks a lot,
    Ramya Shenoy.

    Hi,
    Are you looking for Push and Pull mechanism of PI?
    When the adapters like SOAP, HTTP, IDOC, etc. send the data to PI , it is nothing but a push mechanism, and hence the communication is synchronous by default.
    But adapters like JDBC, File, etc. they fetch the data from Source Applications, so it is a kind of Pull mechanism for PI, and
    by default communication is asynchrnous.
    Pls elaborate exactly what are you looking for?
    Regards,
    Supriya.

  • Actual implementation of interfaces involved in JDBC connection creation

    Pl some body tell me where does the actual implementation of interfaces like connection,Statement,PreparedStatement..we use to to make a JDBC connection from a simple application or J2EE application.
    Thanks

    Hi sharma,
    JDBC API will be implemented by JDBC Driver vendors. For example Microsoft provide "com.microsoft.jdbc.sqlserver.SQLServerDriver" driver for SQL Server 2000. Similarly Oracle privide several JDBC Drivers to be used with Oracle databases.
    Sun has provided a JDBC-ODBC bridge (Driver) along with its JDK or JSDK. This driver is capable for connecting Java applications with any ODBC connection.
    Cuz this driver is included with the JDK/JSDK therefore you can use it to connect with for example MS Access DB or any other ODBC connected DB.
    If you want to connect your Java or J2EE application to some specific database then you should get the Driver for that particular database.
    regards,
    Humayun

  • How to find out in program which all classes have implemented an interface

    Hello,
    I have created an interface and few classes are implementing the interface.
    I want to know in a program which all class have implemented the interface.
    Is it possible to find it out and how?
    Regards,
    Bikash.

    Hi Bikash,
    Read the Database view VSEOIMPLEM with where condition REFCLSNAME = Interface Name and version = 1.
    This would give you all the classes which have implemented the interface and are active...
    If you want to look at the values that the field version can have then see Type Group SEOC ans search for version....
    Hope this help...
    Regards,
    Sitakant

  • How to get classes which implement the interface in program

    Hi,
    I created an interface and some classes are implementing it. I want to know in which classes the interface is implemented through program. I mean in which table the interface implemented details stores.
    please helps regarding this.
    Thanks,
    Regards,
    Priya

    Hi.,
    Read the  database view VSEOIMPLEM with where condition.,  REFCLSNAME =  <Interface Name> and Version = 1.
    This gives the class names which implement the interface.,
    hope this helps u.,
    Thanks & Regards,
    Kiran

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Class constructor that implements an interface returns an  "interface", why

    Hi,
    I am studying some code that I need to understand well. This code works, I just don't understand the following:
    A class was defined extending an interface as so:
    public class GeometricShape implements Area {
    // constructor
    public GeometricShape() {
    System.out.println('bla);
    In another file, GeometricShape class was instantiated as follows:
    public class ExampleUse {
    Area g = new GeometricShape();
    My qustion is, why does the code above expects "new GeometricShape()" constructor to return an interface of type Area?
    Can someone explain?
    thanks

    Can someone explain?When a class implements an interface, or extends another class, or when a interface extends another interface, it means that anywhere an instance of the parent class or interface is expected, the child can be used.
    Wherever a Mammal is expected, you can provide a Dog or Cat or Whale or Human or NakedMoleRat. Each of those is a mammal.
    If you say "give me some food," and you don't specify anything else, the person you're talking to can hand you a hamburger or an apple or a bowl of rice. Any of those will meet the requirements you put forth.
    This is how the OO "is-a" relationship maps to Java.

  • Reg Implementing the interfaces in JDBC

    Hi,
    When we do a program that deals with database connectivity,we are not implementing the Interfaces like Statement,ResultSet.But we are using those
    interfaces inside our program.
    Can anybody justify how it is possible.
    Thanks in advance

    The DB vendors are responsible for providing implementation classes for these interfaces. That's why we need to keep DB specific jar files in CLASSPATH when we do DB activities..
    Gautam

  • Implementing SingleThradModel interface and synchronizing service

    Hi all,
    I came across the one question.
    What is difference between the implementing SingleThradModel interface and synchronizing service method in the Servlet?
    Which one is the better one? and why?
    It seems to be same for me... but still confused?
    Please explain me.
    Thanks,
    Rahul

    No one is better. Just write threadsafe code. E.g. do not declare instance variables which are to be used per request. Just keep in mind that only one instance of the Servlet will be created which lives as long as the webapplication runs and that it will be reused among all requests. Keep request scoped variables inside the method block and you're safe.

  • Implementing Runnable interface  Vs  extending Thread class

    hi,
    i've come to know by some people says that Implementing Runnbale interface while creating a thread is better option rather than extending a Thread class. HOw and Why? Can anybody explain.?

    Its the same amount of programming work...
    Sometimes it is not possible to extend Thread, becuase your threaded class might have to extend something else.
    The only difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas with Runnable, many threads share the same object instance.
    http://developerlife.com/lessons/threadsintro/default.htm#Implementing

  • Implementing Basecommand interface

    hi all,
    i have created a GUI using swing which i want to evoke as a button in ARC map ,but for that i have to implement basecommand interface and use my code there , but iam not getting it how to do that so can any one give me a code snippet or a description soas to how that can be achieved...
    thanks in advance

    Sorry, but there is no BaseCommand interface in the API.
    And what don't you know? What a baseCommand is supposed to do? Neither do I, but if it exists somewhere, it's likely to have a documentation that tells you. Or don't you kno who wto implement interfaces? Then read the tutorial.

Maybe you are looking for

  • An error while deploying from xml

    Hello, all! I've generated xml specification within GUI When I'm trying to deploy it in OMB+ console the error occures OMB05623: Cannot deploy Specification from file. Exception follows. Start of root element expected. OWB 10.1.0.4.0 My steps in OMB+

  • How can i text my friends with my new iphone 4s

    I text a few friends and they advised me that they never recieved it and they text me back and i never recieved their text. what's wrong with this picture?

  • My Home Hub 3 seems to have randomly completely br...

    Tried everything I can. Must be a hardware malfunction. After hours on the phone to BT can't get it to work. Will BT send me another Bt Home Hub 3 for free or will i have to pay?

  • Regarding FK10N

    Hi  Gurus,   We have modified the standard report of FK10N to ZFK10N by adding Profit Center. But the problem i am getting is when i double click on the amonts i shud get the Vendor Line Items Data. But the problem is When i click on Credit amount th

  • BPS Syntax Error

    In BPS, manual planning, I create everything from the area, level, package, to the layout.  For a time, it works fine.  Then without doing anything that I can tell, I start getting error messages.  I can't even delete the area or any component once t