简体   繁体   English

向量IndexOutOfBoundsException

[英]Vector IndexOutOfBoundsException

I am successfully adding the first student but when i add a second one i get 我成功添加了第一个学生,但是当我添加第二个学生时,我得到了
Exception in thread " main " java.lang.ArrayIndexOutOfBoundsException : Array index out of range: 11 线程“ main ”中的异常java.lang.ArrayIndexOutOfBoundsException :数组索引超出范围:11

at java.util.Vector.get(Unknown Source)  
    at business.StudentCollection.UseArray(StudentCollection.java:58  
    at business.Application.main(Application.java:30) 

Segments of code 代码段

 public class StudentCollection {  
private Vector<Student> collection;  
private int count;  

public StudentCollection ()
{  
collection=new Vector<Student>(10,2);  
count=0;  
for( int i=0;i< collection.capacity(); i++) //i read that object cannot be added to 
vectors if empty  
collection.add(i,new Student(0,"No Student",0));

}  

public void addStud(int ID,String name,int Credits)
   {    

for(int i=0;i< collection.capacity();i++)  
 if(collection.get(i)==null)  // new Error
collection.add(i,new Student(0,"No Student",0)); //making sure vector new index are   filled

collection.add(count,new Student(ID,name,Credits));  
count++;  

  }  
public Student UseArray(int x){  \\ Error here line 58
return collection.get(x);  

                      }

 public int getlengthh(){  
    return collection.capacity();  
                }  
}  
 public static void main (String [] args ){  
 StudentCollection C=new StudentCollection();  


        System.out.println("Enter Student's ID");  
        x=scan.nextInt();  
        for (int i=0;i< C.getlengthh();i++){    
if(C.UseArray(i).getID()==x){  // Error here
        System.out.println("A student with this ID already exists.Do you want to overwrite the existing student?yes/no");  
        scan.nextLine();  
        ans=scan.nextLine();  

        if (ans.equalsIgnoreCase("yes")){
            C.delete(x);
        continue;
        }
        else {
            System.out.println("Enter Student's ID");
        x=scan.nextInt();
        }
            }
        }

        System.out.println("Enter Student's name");
        Str=scan.nextLine();
        Str=scan.nextLine()+Str;
        System.out.println("Enter number of credits");
        y=scan.nextInt();
        C.addStud(x,Str,y);

    }

Modify to 修改为

 public Student UseArray(int x){  \\ Error here line 58
     if(collection.size() > x)
        return collection.get(x); 
     return null; 

    }

There is a difference between capacity and size. 容量和大小之间有区别。 Capacity returns length of array created by Vector to hold the present and the incoming elements. Capacity返回由Vector创建的,用于保存当前元素和传入元素的数组的长度。 While size is the number of elements already put into the vector. 而size是已经放入向量中的元素数。 Having said that, While checking for existence of elements don't use capacity use size as below: 话虽如此,当检查元素是否存在时,不使用容量使用大小,如下所示:

 public int getlengthh(){  
    return collection.size();  
                } 

Even if capacity is bigger than index still add can throw exception. 即使capacity大于index仍然会添加抛出异常。 See here 这里

The whole point of collection classes like Vector is that you don't need to manually index into them like an array. Vector这样的集合类的全部要点是,您不需要像数组那样手动索引它们。 You don't need to maintain a count variable, either -- when you want to know how many students you have, simply call size() on the Vector. 您也不需要维护count变量-当您想知道自己有多少学生时,只需在Vector上调用size()即可。 Now, unless you need Vector's thread-safety, I would go with ArrayList instead, but they are both implementations of List, which means all you need to do is call add(Student) . 现在,除非需要Vector的线程安全性,否则我将改用ArrayList,但它们都是List的实现,这意味着您需要做的就是调用add(Student)

I would take a good look at the Java Collections Trail before continuing. 在继续之前,我会仔细看一下Java Collections Trail

Also, on a stylistic note, clean up your source formatting. 另外,在风格上,请清理源格式。 Having inconsistent indentation will make it very hard to review your code for bugs. 缩进不一致会使得很难检查代码中的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM