【问题标题】:Generic Class Iterator泛型类迭代器
【发布时间】:2012-03-01 04:05:42
【问题描述】:

我有三个班级,分别是 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());
    }
}
}

【问题讨论】:

  • 迭代器中的 getData() 方法不是边界检查。尝试:return (index
  • 将来,如果您从示例中删除所有不相关的代码,将会很有用。这称为SSCCE。它还可以帮助您获得答案,因为没有人愿意通过 500 行代码来找到包含错误的单行代码。
  • 我为大量的代码道歉。我只是想提供足够的背景信息。
  • 创建 SSCCE 的过程通常也会为您指明解决方案——学习钓鱼等等。

标签: java class generics iterator


【解决方案1】:

查看您的代码后,我发现了多个问题,如下所示:

  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类的this调用序列中

    print.hasNext() -&gt; current.getData(index)

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

请更正您的代码。

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    相关资源
    最近更新 更多