Creating an ArraySetIterator <E> Class - java

I'm creating an ArraySetIterator Class and having trouble with the next() method.
I have done some research but nothing seems to work for me. I'm sure its a simple piece of code but I can't seem to figure it out....
private class ArraySetIterator <E> implements Iterator <E> {
private ArraySet<E> set;
private int index = 0;
public ArraySetIterator(ArraySet<E> set) {
this.set = set;
}
public boolean hasNext() {
return (index + 1) < set.size();
}
public E next() {
???
}
public void remove() {
set.remove(index);
}
}

next() should increase the index and return the current element. I addition, it should throw NoSuchElementException if there are no more elements left to iterate over.

This works:
public E next() {
return set.get(index++);
}
You might also want to think about checking to see if hasNext() is true.
EDIT: Based on your comment, it sounds like your ArraySet is only implementing the Set interface. So you can't use .get(). I think you need do do something like this instead:
private class ArraySetIterator <E> implements Iterator <E> {
private E[] set;
private int index = 0;
public ArraySetIterator(ArraySet<E> set) {
this.set = (E[]) set.toArray();
}
public boolean hasNext() {
return (index + 1) < set.length;
}
public E next() {
if(hasNext) {
return set[index++];
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}

Related

Implementer Iterator

I am currently trying to implement Iterator which receives a collection and a char and that yields the
Strings that starts with that char.
So I ended up with the following (working) code:
class A {
public static void main (String [] args) {
String [] arr = {"abcd","gr","gres","bvg","bb"};
class FirstCharIt implements Iterator<String> {
char c;
private Iterator<String> it;
public FirstCharIt (Collection<String> lst,char c) {
this.c = c;
this.it = lst.stream().filter(x->{
return (x.charAt(0)==this.c);
}).iterator();
}
#Override
public boolean hasNext() {
return it.hasNext();
}
#Override
public String next() {
return it.next();
}
public Iterator<String> get () {
return it;
}
}
FirstCharIt it1 = new FirstCharIt(Arrays.asList(arr),'b');
for (it1.get();it1.hasNext();) {
System.out.println(it1.next());
}
}
}
Although this code is working this is not actually implementing Iterator interface and I even can remove the 'implements Iterator' from my class headline.
And of course the method get wasn't there in more right implementation
So I would like to have some advice about what I did here,
thanks
Filter the input list at initialization, have that filtered collection and an index as fields of your iterator.
Have hasNext() check if the index has reached the end of the filtered collection, and next() increase the index and return the element it previously pointed at.
static class FirstCharIt implements Iterator<String> {
private int currentIndex;
private List<String> filtered;
public FirstCharIt (List<String> coll, char letter) {
this.filtered = coll.stream().filter(x->x.startsWith(""+letter)).collect(Collectors.toList());
this.currentIndex = 0;
}
#Override
public boolean hasNext() {
return currentIndex < filtered.size();
}
#Override
public String next() {
if (!hasNext()) { throw new NoSuchElementException(); }
return filtered.get(currentIndex++);
}
}
You can try it here.

Class Derived Iterator

What does it mean for an iterator to be derived from a class?
More specifically, I have two classes DNode and DoublyLinkedList. DoublyLinkedList uses DNode to construct the list and I'm using both to create a stack and queue. How do I write a method which returns a class derived iterator?
Here's what I have currently:
public Iterator <E> getCollectionIterator() {
Iterator <E> i = new Iterator <E>() {
private int currentIndex = 0;
#Override
public boolean hasNext() {
return (currentIndex < size && arrayList[currentIndex] != null);
}
#Override
public E next() {
if(hasNext()) {
return arrayList[currentIndex++];
} else
throw new NoSuchElementException("Next element does not exist.");
}
#Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
};
return i;
}

Iterator and iterable for an 2D array Java

I have created two iterators for an array: the first runs the array by rows (iteratorRow) and then by columns and the second, first by columns and then by rows (iteratorColumn).
I have another class, Matrix, in which I must create two methods for performing iteration (iteratorRowColumn and iteratorColumnRow) that return iterators that have created to be accessible to other classes.
The array must implement the Iterable interface and may be configured (using a Boolean) which of the two iterators it shall be refunded by calling iterator () method.
How can I do that? Do I have to do some getters methods? Something like this?
public Iterator iteratorRowColumn () {
return new iteratorRow;
}
I think that the last sentence of assignment explains a problem very well. I am not sure what part of it is unclear so let me explain in detail:
The array must implement the Iterable interface
public class Matrix<T> implements Iterable<T>
may be configured (using a Boolean)
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
which of the two iterators it shall be returning by calling iterator() method
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
Here is a compilable example:
public class Matrix<T> implements Iterable<T> {
T[][] array;
boolean defaultRowColumnIterator;
public Matrix(boolean defaultRowColumnIterator) {
this.defaultRowColumnIterator = defaultRowColumnIterator;
}
// other methods and constructors
public Iterator<T> iteratorRowColumn() {
return null; // your current implementation
}
public Iterator<T> iteratorColumnRow() {
return null; // your current implementation
}
#Override
public Iterator<T> iterator() {
return defaultRowColumnIterator ? iteratorRowColumn() : iteratorColumnRow();
}
}
Something like this:
public class Proba {
Integer[][] array = new Integer[10][10];
public class MyIter implements Iterator<Integer> {
private Integer[] integers;
private int index = 0;;
public MyIter(Integer[] integers) {
this.integers = integers;
}
#Override
public boolean hasNext() {
return index < integers.length -1 ;
}
#Override
public Integer next() {
return integers[index];
}
#Override
public void remove() {
//TODO: remove
}
}
public static void main(String[] args) {
Iterator<Integer> iter = new Proba().getIterator(1);
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
public Iterator<Integer> getIterator(int row) {
return new MyIter(array[row]);
}
}

Cannot implement next() method throught iterator

I am trying to implement the next() method through an interface, however it is giving me an error. Here is what I have:
private class MyIterator implements Iterator<Term>
{
private final Polynomial myArray;
private int current;
MyIterator(Polynomial myArray) {
this.myArray = myArray;
this.current = myArray.degree;
}
#Override
public boolean hasNext() {
return current < myArray.degree;
}
#Override
public Integer next() { //this method right here does not work
if (! hasNext()) throw new UnsupportedOperationException();;
return myArray.coeff[current++];
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
The next() method then throws me this error :
And this is my interface:
public interface Term {
int coeff();
int exp();
String toString();
}
So my question is why the interface does not allow the MyIterator to implement the next() method
Your class is implementing Iterator<Term>, so next() must return a Term, not an Integer.
Edit: This line
if (! hasNext()) throw new UnsupportedOperationException();;
is wrong. If the Iterator has no more items, next() must throw a NoSuchElementException.
The Iterator<Term> promises that your iterator will return references of type Term, but your next() method attempts to return Integer.
One of the two things needs to change to be consistent with the other one.

Java list best practice

I need some container to keep elements so, if I'll try to get the size()+i element, i'll get element number i. Or with iterator, which starts from the beginning of container after it tries to get the last element? What are the best practicies in both cases? I mean performance and easy useability.
You could create a simple subclass of ArrayList<T> and override the get(int n) method as follows:
public T get(int n)
{
return super.get(n % this.size());
}
As to the iterator, you will need to implement your own, which shouldn't be all that hard.
EDIT:
Assuming your new class is called RingList, here's a sample RingIterator (untested):
public class RingIterator<T> implements Iterator<T>
{
private int cur = 0;
private RingList<T> coll = null;
protected RingIterator(RingList<T> coll) { this.coll = coll; }
public boolean hasNext() { return size() > 0; }
public T next()
{
if (!hasNext())
throw new NoSuchElementException();
int i=cur++;
cur=cur%size();
return coll.get(i);
}
public void remove() { throw new UnsupportedOperationException(); }
}
You would then override the iterator() method in RingList<T> as
public Iterator<T> iterator()
{
return new RingIterator(this);
}
For the first part, just ask for n % list.size() perhaps?
For the iterator part, create a class that wraps an iterator, and when next() returns null, just have it reset the iterator.
Thanks everyone, thats what I've created:
public class RingIterator<E> {
private List<E> _lst;
private ListIterator<E> _lstIter;
public RingIterator(ListIterator<E> iter, List<E> lst) {
super();
_lstIter = iter;
_lst = lst;
}
public E next() {
if(!_lstIter.hasNext())
_lstIter = _lst.listIterator();
return _lstIter.next();
}
public E previous() {
if(!_lstIter.hasPrevious())
_lstIter = _lst.listIterator(_lst.size());
return _lstIter.previous();
}
}
Then get method:
/*
* Returns ring iterator,
* use it with 'ParentClass' type.
*/
public RingIterator<SubClass> getRingIter(int i) {
return new RingIterator(_subs.listIterator(i),_subs);
}
And I use it:
RingIterator<SubClass> ri = _logic.getRingIter(1);
ParentClass ai = ri.next();
I wanted to make only type ParentClass (not SubClass) available via getRingIter, but I don't see a way to do it with no creation of List - convertion of List.
Extend the ArrayList class and implement the get(Integer) method the way you like. I think this is the 'best practice'.

Categories

Resources