Java无法识别ArrayList中的元素?

3
我有一个程序,其中我创建了一个ArrayList来存储一些出租车对象。我一直收到一个错误消息,说Java无法识别ArrayList中是否有对象。这是我得到的错误信息:
异常线程“main”java.lang.IndexOutOfBoundsException:索引:20,大小:20 在java.util.ArrayList.rangeCheck(未知来源) 在java.util.ArrayList.get(未知来源) 在edu.Tridenttech.MartiC.app.CabOrginazer.main(CabOrginazer.java:48)
这是我正在尝试使其工作的代码。
public class CabOrginazer {

private static List<CabProperties> cabs = new ArrayList<CabProperties>();
private static  int count = 0;
private static boolean found = false;


public void cabOrginazer() 
{

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    CabRecordReaper reaper = new CabRecordReaper("C:/CabRecords/September.txt");
    CabProperties cabNum;

    for(int i = 0; i < 20; i++)
    {
        cabNum = new CabProperties();
        cabs.add(cabNum);
    }
    while(reaper.hasMoreRecords())
    {
            CabRecord file = reaper.getNextRecord();
            for(int j = 0; j < cabs.size(); j++)
            {
                if(cabs.get(j).getCabID() == file.getCabId())
                {
                    found = true;
                    cabs.get(j).setTypeAndValue(file.getType(), file.getValue(), file.getPerGallonCost());
                    cabs.get(j).setDate(file.getDateString());
                    break;
                }

            }

            if(found == false)
            {
                cabs.get(count).setCabId(file.getCabId());
                count++;
            }
            /*for(CabProperties taxi : cabs)
            {
                if(taxi.getCabID() == file.getCabId())
                {
                    found = true;
                    taxi.setTypeAndValue(file.getType(), file.getValue(), file.getPerGallonCost());
                    taxi.setDate(file.getDateString());
                    break;
                }


            }*/

    }


    for(CabProperties taxi : cabs)
    {
        System.out.print("cab ID: " + taxi.getCabID());
        System.out.print("\tGross earning: " +  taxi.getGrossEarn());
        System.out.print("\tTotal Gas Cost: " + taxi.getGasCost());
        System.out.print("\tTotal Service Cost: " +  taxi.getServiceCost());
        System.out.println();

    }


}

}

第48行 是if语句的内部,其中包含cabs.get(count).setCabId(file.getCabId());。根据我对Java的了解,Java应该知道cabs中有元素,并且我应该能够设置出租车的id。是什么原因导致Java无法识别ArrayList已填充呢?

2个回答

7
列表并没有在第count项中放置一个元素。看一下异常:列表中有20个元素,因此有效的索引是0到19(包括)。你正在请求第20个记录(即第21个记录),这个不存在。
听起来你的代码块应该像这样:
if (!found)
{
    CabProperties properties = new CabProperties();
    properties.setCabId(file.getCabId());
    // Probably set more stuff
    cabs.add(properties);
}

你完全可以完全去掉count变量,以及使用虚拟属性初始化列表的步骤。既然你使用的是 List 而不是数组 array,可以直接跳过这一步。使用 List, 特别是 ArrayList,最大的好处就是它们具有动态大小。

4

Java能够正确识别数组成员。你的数组里有20个成员,从索引0到索引19。

你正在请求索引20,但它并不存在。

这是一个for循环:

while(reaper.hasMoreRecords())

您可能需要运行比预期更多次,您的数据会多次触发 found == false 的条件(您可以简单地写成 if (!found) { ...),并在第21次时由于索引越界异常而失败。

您还应该了解如何使用调试器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接