Relationship between class and iterator interface - java

Will a class become an iterator object itself if it implements an iterator interface.
For example,
public class StringGridIterator implements Iterator<String>{
//some methods here...
}
or Do I need to specifically create a variable reference to an iterator object that will iterate through a certain String objects?
like this...
Iterator<String> it = object.iterator();
I don't know if this is clear enough for you to understand since I am still struggling with understanding Java concept like class and object myself.. Just leave a comment if you don't understand what I am trying to say.

A class will not become an Iterator object by implementation. You may be thinking of extending a class. (See: What's the difference between the implements & extends keywords in Java).
From your examples, it looks like you are attempting to do 2 different things: class inheritance vs. an iterator object. The .iterator() method returns an Iterator containing the elements of your object.

Related

Iterable and Iterator in java

Here is my understanding on significance of using Iterable and Iterator in pre 1.8 java.
1)
java.util.AbstractList is Iterable because it implements,
Iterator<T> iterator();, which is a contract for any class to be Iterable.
2)
java.util.AbstractList implements,
Iterator<T> iterator(); by creating an instance level inner class,
private class Itr implements Iterator<E> { ... }
that implements hasNext, next and remove methods.
private class ListItr extends Itr implements ListIterator<E>{..} is just an extra facility over above iterator for List type implementations.
3)
Is this the only purpose of these two interfaces Iterable & Iterator, to enable any object to be iterable? Please let me know, if there is any other purpose of these two interfaces?
You are right stating what these interfaces are used for. Indeed Iterable declares that the objects of a class implementing it may be iterated over, by providjng an Iterator specific to these objects. Having them is necessary because how exactly the object should be iterated depends on its internal implementation, and an Iterator is therefore specific to a given "collection" class.
Having said that, it is worth noting that although these interfaces are formally a part of Java Collections framework, they can be applied to other cases. Given an imaginary API to read CSV files for example, one can declare a CsvFile class to implement an Iterable<List<String>> and iterate over lines in a file with a dedicated Iterator<List<String>> which will read lines from the file one-by-one and split them into a List of Strings to return it from next().
Another important purpose of these interfaces is a language feature known as "for each" loop - only objects of a class implementing Iterable can be iterated with it. So, given an example from above about CsvFile API, it will also enable something like:
CsvFile csvFile = new CsvFile(pathToCsvFile);
for (List<String> record : csvFile) {
doSomethingWithIt(record);
}
As "for each" loop is purely a language feature, compiler will expand it to use an Iterator as usual.
P.S. Just because it hurts my eyes, I'd like to add that in the example above I would also suggest implementing an AutoCloseable for the CsvFile and using it with try-with-resources.
java.util.Collection interface extends to java.util.Iterable. Iterable has a method that produces the iterator. If any class implements iterable, it has an iterator method that produces java.util.Iterator.
Please refer to this post
If you check out interface Iterable it has only one method that is Iterator<T> iterator();. So there is no other possible use case for implementing Iterable interface other than providing iterator method.
If you see the documentation of Iterator interface, in See Also section you will find Collection, ListIterator, Iterable. Collection and ListIterator are by default Iterable as they internally extend Iterable. So Iterable is used in conjunction with Iterator.

Creating custom Iterator Java?

I'm a bit confused about how to implement a custom iterator for a class in Java. I'm required to essentially make an ArrayList without using the inbuilt libraries already available to me. I understand the basics of creating the class but I'm having trouble understanding how to get the Iterator to fit into all of this. I have the following:
I have created a generic class that implements the iterable interface as such it looks something like this:
public class MyArrayList<T> implements Iterable<T> {
I've then got to create a class called MyIterator which according to the wording of the document is a stand alone class. This seems fairly straight forward I make a new class called MyIterator and have it implement the iterator interface so it looks something like this:
public class MyIterator<T> implements Iterator<T>{
My confusion lies in the following. The document says that the Iterator needs to be in it's own class, but how then do I access the data members in "MyArrayList" to fully implement hasNext() and next() for example. As the data members in the underlying array are private (as they should be) I don't see how an external class can fully implement these methods. Am I misunderstanding what is required? By separate class is it still a part of the "MyArrayList" class but defined differently?
I hope that helps, as I said I think I understand what is required of me I just am not exactly sure where my Iterator fits into all of this.
While the iterator has to be a separate class *, that class will probably have some relation to your Iterable class.
It's often a nested/inner class, precisely because it needs to access the values of the class (and that's what pretty much what inner classes are made for).
Granted, if the Iterable is a List you could implement an Iterator without any "internal" access at all, but you usually still want to get access to the internals for things like checking the modCount (to throw a ConcurrentModificationException when the Iterable is structurally modified while you iterate over it ... and to prevent that exception if you modify it via the Iterator itself).
* you could implement it with your Iterable instance itself, but that would break the contract as soon as the user uses two iterators at the same time.
You have to declare your own methods hasNext(), next(), remove(). It has to know how to iterate over your own class, how to go to next element and how to check whether next element exists.

Implements interface java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an interface in Java?
I have experience with object languages and object paradigm, but I have one doubt about "implements" statement. Doubt is does it includes code (functionality)? So to be very specific Does "MyClass implements XInterface" include code from other classes that implement that interface?
Class inheriting is simple including code, in a way, I know "including" may not be right word but that is what is talking place when you use "extends". You include functionality from parent class.
So let use Runnable interface for example. It has only one run() deceleration. Which could mean nothing, just that MyClass will have implementation of run(). And that what confuses me, like implementing one line deceleration in some file will make me some good... where is the actual functionality (and code) that I will get by using "implements"? So if I use:
MyClass implements Runnable {}
Runnable obj = new (Runnable) MyClass();
obj.run();//will call run() implementation from MyClass
obj.otherFunctions();/* so this calls functions from other classes that implement interface, but I don't know what functions from other classes are implementing, or even do I need them?*/
Also do I have to have one class per thread, like MyClass extends Thread implements Runnable ?
A class Cl that implements an Interface means that all methods that are defined in the interface must be implemented in class Cl. The calling class then can call these methods, because it is known that Cl implements (fullfills) the interface.
For example see the List interface: ArrayList and LinkedList both implement List, they have the same public methods (e.g add(), get()), but are internally working different.
List list = new ArrayList();
list.add(3);
later if somebody wants ArrayList to be exchanged by another class, that also implements List, only one line has to be exchanged
List list = new LinkedList();
list.add(3);
If programming to Interfaces the code is less dependent on a specific class. this has advantages when you later want to exchange one class for e,g purpose of testing, where you could controll that class by a test case.

How does Iterator ties into Collection Interface

I am new to Java.
Java has Collection interface
public interface Collection<E> extends Iterable<E>
{ // a lot of other stuff.
Iterator<E> iterator(); }
What I don't understand is how does Iterator Interface is tying into Collection Interface ? When I look at the Collection Interface, I see that it has a method that returns Iterator. When Iterator for Collection is created, where does JVM looks to create an object that IS-An Iterator ?
Thanks !
The JVM doesn't do it; the code that ultimately implements the abstract iterator() method just creates an instance of an appropriate class and returns it. For example, in the class ArrayList(), which implements List which extends Collection, there is a method that implements iterator() by returning an instance of a class that understand how ArrayList is implemented internally. This Iterator class is private to the java.util package -- normally you'll never see its name.
Ok so this is all pretty advanced java stuff and it will be pretty tough to explain in one go here but I will do my best.
BACKGROUND: If you don't know about those funny <E> things, you should do a bit of looking into Java Generics. Also, if you don't already, you really need to know what an interface is. One really basic way to think of it is as a promised bit of functionality a class promises to provide.
Now to answer your question: There are three interfaces in the above code snippet, and if you want to create your own collection class you will need to provide implementations of all three:
The first is Collection. This is a simple concept that maps to the real world, it is literally a "collection" of objects. I think you get this...
The next one is Iterable this defines a singe type of behavior that all collections need to provide: the ability to traverse all of the elements of a collection, while accessing them one by one ie "iterate" over them. But it doesn't stop there. As you pointed out the Iterable functionality is provided by objects that implement the last interface:
Iterator: objects that implement this interface, actually know how to traverse the elements of a collection class, they hide all the details of how its actually done from thier clients and proved a few clean easy methods for actually doing it like hasNext() which checks to see if there are more things in the collection to visit and next() which actually visits the next thing.
phew...
The code for the iterator() method determines which concrete implementation of Iterator to return.
All non-abstract classes that implement the Collection interface are required to provide an implementation for the iterator() method.

What is a public interface?

"Using only the public interface of the linked list class, write a method
public static void reverse(LinkedList staff)
that reverses the entries in a linked list."
The part of all of that I'm not understanding is the first part. What does it mean by public interface of linked list class? Do I create a new class file that starts with something like public interface linkedlist? Can I add the method as a inner class within my main class?
The question is unnecessarily vague. What it's trying to ask is "using only the methods and fields of LinkedList that have the access modifier public, write this method."
You can put the method you write in any class you like, but the restriction says that you may only use public methods and fields on LinkedList to write it.
This also means that you can't create a subclass of LinkedList and use its protected methods.
The public interface of a class are its public properties (variables or fields you can read the values of or assign to) and methods (functions you can call).
So, the assignment is to create something that is not a subclass of LinkedList. Creating a subclass would give you access to protected methods for example. You need to create something external to LinkedList, for example:
void MyMethod()
{
LinkedList l = new LinkedList();
// do something with l here.
}
"Public interface of linked list class" means only public methods of the LinkedList class. See the javadoc, there is a list of all public methods, or create new LinkedList instance and let your IDE suggest.

Categories