bob9123
bob9123

Reputation: 745

Making/Implementing a Iterator for arraylists- Java

Code for MyArrayList class:

public class MyArrayList implements Iterable<Object> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
private int currentSize;

public MyArrayList() {
    size = 0;
    capacity = DEFAULT_SIZE;
    items = new Object[DEFAULT_SIZE];
    this.currentSize = items.length;
}

@Override
public Iterator<Object> iterator() {
    Iterator<Object> it = new Iterator<Object>() {
        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            return currentIndex < currentSize && items[currentIndex] != null;
        }

        @Override
        public Object next() {
            return items[currentIndex++];
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    };
    return it;
}


        private void expand() {
            Object[] newItems = new Object[capacity + EXPANSION];
            for (int j = 0; j < size; j++) newItems[j] = items[j];
            items = newItems;
            capacity = capacity + EXPANSION;
        }

        public void add(Object obj) {
            try {
                if (size >= capacity) this.expand();
                items[size] = obj;
                size++;
            } catch (IndexOutOfBoundsException e) {
                System.out.println("There is an error adding this word." + e.getMessage());
            }
        }

        public int size() {
            return size;
        }

        public Object get(int index) {
            try {
                return items[index];
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("There is an error getting this word from position: " + e.getMessage());
            }
            return items[index];
        }


        public void add(int index, Object obj) {
            try {
                if (size >= capacity) this.expand();
                for (int j = size; j > index; j--) items[j] = items[j - 1];
                items[index] = obj;
                size++;
            } catch (IndexOutOfBoundsException e) {
                System.out.println("There is an error adding this word to array at position: " + e.getMessage() + ".");
            }
        }


        public boolean remove(Object obj) {
            for (int j = 0; j < size; j++) {
                if (obj.equals(this.get(j))) {
                    for (int k = j; k < size - 1; k++) items[k] = items[k + 1];
                    items[size] = null;
                    size--;
                    return true;
                }
            }
            return false;
        }

        public Object remove(int index) {
            try {
                Object result = this.get(index);
                for (int k = index; k < size - 1; k++) items[k] = items[k + 1];
                items[size] = null;
                size--;
                return result;
            } catch (IndexOutOfBoundsException e) {
                System.out.print("There is an error removing this word from position " + e.getMessage());
            }
            return null;
        }
 }

 }

Code for main method. (adding data)

 public class adding{

static MyArrayList zoo = new MyArrayList() {


public static void printZoo() {
    System.out.print("The zoo now holds " + zoo.size() + " animals: ");
    for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
    System.out.println();
}
public static void main(String[] args) {

    String[] zooList = {"Cheetah", "Jaguar", "Leopard", "Lion", "Panther", "Tiger"};

    for (String x: zooList) zoo.add(x);
    printZoo();

    System.out.printf("\nTesting the iterator\n>> ");
    Iterator it = zoo.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + " ");
    }
    System.out.println();

    System.out.printf("\nTesting the iterator again without resetting\n>> ");
    while (it.hasNext()) {
        System.out.print(it.next() + " ");
    }
    System.out.println();

    System.out.printf("\nTesting the iterator again after resetting\n>> ");
    it = zoo.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + " ");
    }
    System.out.println();

    System.out.printf("\nTesting for-each loop\n>> ");
    for(Object animal: zoo) System.out.print(animal + " ");
    System.out.println();

    System.out.println("\nLetting all the animals escape");
    while (zoo.size()>0) zoo.remove(0);
    printZoo();

    System.out.printf("\nTesting the iterator with an empty list\n>> ");
    it = zoo.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + " ");
    }
    System.out.println();

    System.out.println("\nTest complete");


}
 }

So I need to make a correct Iterator so it can print out the contents of the arraylists using the while loops.

OUTPUT

 The zoo now holds 6 animals: Cheetah Jaguar Leopard Lion Panther Tiger 

 Testing the iterator
 >> Cheetah Jaguar Leopard Lion Panther  //Works fine

 Testing the iterator again without resetting
 >>  // This is still blank

Testing the iterator again after resetting
>> Cheetah Jaguar Leopard Lion Panther 

Testing for-each loop
>> Cheetah Jaguar Leopard Lion Panther // Works fine.

Letting all the animals escape
The zoo now holds 0 animals: //Is there a way to remove by changing the MyArraylist class instead of changing the added class?

Testing the iterator with an empty list
>> Tiger  //Still inaccurate.

Pretty sure the logic of my iterator from the MyArrayList class is not accurate.

Upvotes: 1

Views: 6338

Answers (3)

Ueli Hofstetter
Ueli Hofstetter

Reputation: 2524

By using

  static MyArrayList zoo = new MyArrayList() {
        @Override
        public Iterator<Object> iterator() {
            return null;
        }
    };

you declare a new anonymous inner class which overrides the iterator method you defined in MyArrayList. So just construct zoo as

static MyArrayList zoo = new MyArrayList(); 

and it should be fine (apart from the expand method which is missing in the snippet you posted)

Upvotes: 1

meneken17
meneken17

Reputation: 348

Well.. It does exactly what it is supposed to do.

You have overridden the iterator() method with a null return as you declared zoo (Adding.java line 7-12).

So the iterator is null and java will throw a NullPointerException as soon as you try to acess a method of the Iterator.

2 little things to notice. Please provide all methods (expand() was missing) and follow the name convetions (class names with capital letter).

Upvotes: 0

muzilihao
muzilihao

Reputation: 16

You just override the Iterable<Object> interface in your main class which return a null iterator.

Change your code

static MyArrayList zoo = new MyArrayList() {
@Override
public Iterator<Object> iterator() {
    return null;
}};

To

static MyArrayList zoo = new MyArrayList();

Upvotes: 0

Related Questions