制作/实现arraylists的迭代器 - Java

时间:2015-03-31 01:28:24

标签: java arraylist iterator iterable

MyArrayList类的代码:

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;
        }
 }

 }

主要方法的代码。 (添加数据)

 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");


}
 }

所以我需要制作一个正确的迭代器,以便它可以使用while循环打印出arraylists的内容。

输出

 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.

非常确定MyArrayList类中我的迭代器的逻辑是不准确的。

3 个答案:

答案 0 :(得分:1)

使用

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

你声明一个新的匿名内部类,它覆盖你在MyArrayList中定义的迭代器方法。所以只需将动物园建成

static MyArrayList zoo = new MyArrayList(); 

它应该没问题(除了你发布的代码片段中缺少的扩展方法)

答案 1 :(得分:0)

您只需覆盖主类中返回null迭代器的Iterable<Object>接口。

更改您的代码

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

static MyArrayList zoo = new MyArrayList();

答案 2 :(得分:0)

嗯..它完全符合预期。

在声明zoo(Adding.java第7-12行)时,您已使用null返回重写了iterator()方法。

因此,迭代器为null,只要您尝试访问Iterator的方法,java就会抛出NullPointerException。

要注意的两点小事。请提供所有方法(expand()缺失)并遵循名称对话(带有大写字母的类名)。