0

this is my first question here. I have played around a little and created a class named MyIterator which implements the interface Iterator. Everything works great when I use it with the following array :

String u [] = {"Hello", "Whats", "Up"};
MyIterator <String> strins = new MyIterator <> (u);
    while(strins.hasNext()) {
        System.out.print(strins.next() + " ");
    }

It works perfectly but it just doesn't work when I use an Integer array..

Integer array[] [] = new Integer [3] [3];
    for (int i=0; i<3; i++) {
        for (int t=0; t<3; t++) {
            array[i] [t] = 3;
        }
    }

MyIterator <Integer> it = new MyIterator <> (array);
    while(it.hasNext()) {
        System.out.println(it.next());
    }

Here is my MyIterator class guys :

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyIterator <E> implements Iterator <E> {

    private int i;
    private E a[];

    public MyIterator(E a[]) {
        i=0;
        this.a=a;
    }

    public boolean hasNext() {
        return i<a.length;
    }

    public E next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        } else {
            return a[i++];
        }
    }
}

It says : Cannot infer type arguments for MyIterator<>

I would be very happy if people could help me since learning java is harder when the university is closed :(

If you guys see other things that could be improved, please tell me :)

Hello
  • 1
  • 1
    Shouldn't `MyIterator it = new MyIterator <> (array);` be `MyIterator it = new MyIterator <> (array);` as in `Integer[]` not, `Integer`? – omajid Apr 30 '20 at 16:06

1 Answers1

1

The Problem is that you are not creating a normal Integer array, but instead a 2D Integer array Integer array[][]

So if you want to iterate over that 2D array you have to Iterate over the outer array or Integer[]:

MyIterator <Integer[]> it = new MyIterator <> (array);

If you want to also iterate the inner Integer array you will need to use 2 nested MyIterator objects:

final MyIterator<Integer[]> it = new MyIterator<>(array);
while (it.hasNext()) {
    final MyIterator<Integer> itInner = new MyIterator<>(it.next());
    while (itInner.hasNext()) {
        System.out.println(itInner.next());
    }
}
OH GOD SPIDERS
  • 3,091
  • 2
  • 13
  • 16
  • thank you a lot ! I tried the iteration on the outer array but instead of the expected solution i get : [Ljava.lang.Integer;@4517d9a3 [Ljava.lang.Integer;@372f7a8d [Ljava.lang.Integer;@2f92e0f4 What can I do to receive my normal solution instead of the addresses(?) ? – Hello Apr 30 '20 at 16:26
  • That is because Arrays use the default Object `toString()` method and don't override it. If you want to print an array see [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – OH GOD SPIDERS Apr 30 '20 at 16:30