通用类迭代器

时间:2012-03-01 04:05:42

标签: java class generics iterator

我有三个课程,分别是ListerObjectSortedListSortedListProgram。我遇到了泛型类的迭代器问题。我究竟做错了什么?

这是我得到的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at objectsortedlist.ObjectSortedList.getData(ObjectSortedList.java:122)
    at objectsortedlist.Lister.hasNext(Lister.java:28)
    at objectsortedlist.SortedListProgram.main(SortedListProgram.java:52)
Java Result: 1

以下是我的课程:

package objectsortedlist;

import java.util.Iterator;

/**
*
* @author Steven
*/
public class ObjectSortedList<T> implements Cloneable, Iterable<T> {

private T[] data;
private int capacity;

public ObjectSortedList()
{
    final int init_capacity = 10;
    capacity = 0;
    data = (T[])new Object[init_capacity];
}

public ObjectSortedList(int init_capacity)
{
    if(init_capacity < 0)
        throw new IllegalArgumentException("Initial capacity is negative: " + init_capacity);
    capacity = 0;
    data = (T[])new Object[init_capacity];
}

private boolean empty()
{
    if(data.length == 0 || data[0] == null)
        return true;
    else
        return false;
}

public int length()
{
    return capacity;
}

public void insert(T element)
{
    if(capacity == data.length)
    {
        ensureCapacity(capacity * 2 + 1);
    }
    data[capacity] = element;
    capacity++;
}

public boolean delete(T target)
{
    int index;

    if(target == null)
    {
        index = 0;
        while((index < capacity) && (data[index] != null))
            index++;
    }
    else
    {
        index = 0;
        while((index < capacity) && (!target.equals(data[index])))
            index++;
    }

    if(index == capacity)
        return false;
    else
    {
        capacity--;
        data[index] = data[capacity];
        data[capacity] = null;
        return true;
    }
}

private void ensureCapacity(int minCapacity)
{
    T[] placeholder;

    if(data.length < minCapacity)
    {
        placeholder = (T[])new Object[minCapacity];
        System.arraycopy(data, 0, placeholder, 0, capacity);
        data = placeholder;
    }
}

public ObjectSortedList<T> clone()
{
    // Cloning
    ObjectSortedList<T> answer;

    try
    {
        answer = (ObjectSortedList<T>) super.clone();
    }
    catch(CloneNotSupportedException cnse)
    {
        throw new RuntimeException("This class does not implement cloneable.");
    }

    answer.data = data.clone();
    return answer;
}

@Override
public Iterator<T> iterator() 
{
    return (Iterator<T>) new Lister<T>(this, 0);
}

public T getData(int index)
{
    return (T)data[index];
}
}


package objectsortedlist;

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

/**
*
* @author Steven
*/
public class Lister<T> implements Iterator<T>
{
private ObjectSortedList<T> current;
private int index;

public Lister(ObjectSortedList<T> top, int index)
{
    current = top;
    this.index = index;
}

@Override
public boolean hasNext()
{
    return (current.getData(index) == null);
}

@Override
public T next()
{
    T answer;

    if(!hasNext())
        throw new NoSuchElementException("The Lister is empty.");

    answer = current.getData(index+1);
    return answer;
}

@Override
public void remove() {
    throw new UnsupportedOperationException("Don't use this. Use objectsortedlist.SortedList.delete(T target).");
}
}


package objectsortedlist;

import java.util.Scanner;

/**
*
* @author Steven
*/
public class SortedListProgram {

private static Scanner scan = new Scanner(System.in);
private static String[] phraseArray = {"Hullabaloo!", "Jiggery pokery!", "Fantastic!", "Brilliant!", "Clever!", "Geronimo!", "Fish sticks and custard.", "Spoilers!",
         "Exterminate!", "Delete!", "Wibbly-wobbly!", "Timey-wimey!"};
private static Lister<String> print;

public static void main(String args[])
{
    int phraseNo = 0;

    System.out.println("I'm gonna say some things at you, and you're going to like it."
            + " How many things would you like me to say to you? Put in an integer from 1-12, please.");
    try
    {
        phraseNo = Integer.parseInt(scan.nextLine());

        while((phraseNo < 1) || (phraseNo > 12))
        {
            System.out.println("The integer you entered wasn't between 1 and 12. Make it in between those numbers. Please? Pleaseeeee?");
            phraseNo = Integer.parseInt(scan.nextLine());
        }
    }
    catch(NumberFormatException nfe)
    {
        System.out.println("C'mon, why don't you follow directions?");
        phraseNo = 0;
    }

    if(phraseNo == 0);
    else
    {
        ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
        for(int i = 0; i < phrases.length(); i++)
        {
            phrases.insert(phraseArray[i]);
        }

        print = new Lister<String>(phrases, phraseNo);
        while(print.hasNext())
            System.out.println(print.next());
    }
}
}

1 个答案:

答案 0 :(得分:0)

在查看您的代码后,我发现了多个问题,这里是:

  1. SortedListProgram课程中,在以下代码中,phrases.length()将为0,因此它永远不会进入该循环。

    ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
    for(int i = 0; i < phrases.length(); i++)
    {
        phrases.insert(phraseArray[i]);
    }
    
  2. 此外,在SortedListProgram类的此调用序列

    print.hasNext() -> current.getData(index)

    传递的index等于size数组字段的data ObjectSortedList类和因为java数组索引的范围来自 zeroarray size -1。所以你一定会得到 始终java.lang.ArrayIndexOutOfBoundsException

  3. 请更正您的代码。