2014-10-01 67 views
3

我有一个程序,我用一个数组列表来存放一些驾驶室物体。我一直得到一个错误,我从消息中得到的是,java不能识别数组列表中有对象。这是我得到的错误。Java不识别ArrayList中的元素?

异常在线程 “主” 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(); 

    } 


} 

} 

line 48是if语句的内部,它表示cabs.get(count).setCabId(file.getCabId()); 与我对Java的一点知识。 Java应该知道cabs中有元素,我应该可以设置cab的id。什么会导致Java不能识别ArrayList被填充?

回答

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(如ArrayList)的主要好处之一是它的动态大小。

4

Java认识到成员就好。您在阵列中有20个成员,从索引0到索引19索引。

您在索引20,它不存在。

的循环:

while(reaper.hasMoreRecords()) 

比您预期必须运行多少次,你的数据更是创下了found == false如果条件(你只能说if (!found) { ...)很多次,在第21次它会因索引超出范围异常而失败。

你应该弄清楚如何使用你的调试器。