2015-03-31 5 views
1

Код для MyArrayList класса:Изготовление/Реализация итератора для arraylists- Java

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


} 
} 

Так что мне нужно сделать правильный итератора поэтому он может распечатать содержимое 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 класса не является точным.

ответ

1

С помощью

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

вы объявляете новый анонимный внутренний класс, который переопределяет метод итератора вы определили в MyArrayList. Так что просто построить зоопарк, как

static MyArrayList zoo = new MyArrayList(); 

и она должна быть тонкой (помимо расширения метода, который отсутствует в сниппет вы публикуемый)

+0

Ahh забыл удалить этот дополнительный раздел. Огромное спасибо. Теперь по какой-то причине он не повторяет 100% правильно. Я отправлю вывод. (добавлено расширение btw) – bob9123

+0

Я добавил изменения, надеюсь, исправить эти проблемы –

+0

Спасибо за ваши ответы. Пожалуйста, см. Edit – bob9123

0

Вы просто переопределить интерфейс Iterable<Object> в основном классе, который возвращает нулевой итератор.

Изменить код

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

Для

static MyArrayList zoo = new MyArrayList(); 
0

Ну .. Это именно то, что он должен делать.

Вы переопределили метод iterator() с нулевым возвратом, как вы объявили зоопарк (Adding.java line 7-12).

Таким образом, итератор равен null, и java будет вызывать исключение NullPointerException, как только вы попытаетесь использовать метод Iterator.

2 мелочи, чтобы их заметить. Пожалуйста, предоставьте все методы (expand() отсутствует) и следуйте указаниям convetions (имена классов с заглавной буквой).

+0

Хорошо, спасибо, разобрали все. Возникает другая проблема, которую я добавил к описанию – bob9123