【问题标题】:Making/Implementing a Iterator for arraylists- Java为arraylists-Java制作/实现迭代器
【发布时间】:2015-06-04 05:30:13
【问题描述】:

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 循环打印出数组列表的内容。

输出

 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 类中的迭代器的逻辑不准确。

【问题讨论】:

    标签: java arraylist iterator iterable


    【解决方案1】:

    通过使用

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

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

    static MyArrayList zoo = new MyArrayList(); 
    

    应该没问题(除了你发布的sn-p中缺少的expand方法)

    【讨论】:

    • 啊忘记删除多余的部分了。非常感谢。现在由于某种原因,它没有正确地迭代 100%。我会发布输出。 (添加了展开顺便说一句)
    • 我添加了更改以希望解决这些问题
    • Ok... 那里似乎有点乱 ;-) 使用两个变量来跟踪 MyArrayList 类的大小(即 size 和 currentsize)肯定是错误。我建议您使用列表而不是数组来跟踪“MyArrayList”中的项目。这样做您可以摆脱围绕数组内容复制的所有代码。这也可以让您摆脱 currentsize 变量,因为您可以随时查询有关当前大小的列表。
    • 好的,谢谢大家的帮助。
    【解决方案2】:

    您只需覆盖主类中的Iterable&lt;Object&gt; 接口,该接口返回一个空迭代器。

    更改您的代码

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

    static MyArrayList zoo = new MyArrayList();
    

    【讨论】:

      【解决方案3】:

      嗯..它确实做了它应该做的事情。

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

      所以迭代器为空,一旦你尝试访问迭代器的方法,java 就会抛出 NullPointerException。

      需要注意的 2 件小事。请提供所有方法(expand() 缺失)并遵循名称约定(大写字母的类名)。

      【讨论】:

      • 好的,谢谢,一切都解决了。我在描述中添加了另一个问题
      猜你喜欢
      • 2016-06-15
      • 2012-12-05
      • 1970-01-01
      • 2016-09-27
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      相关资源
      最近更新 更多