[英]IndexOutOfBoundsException: 0>=0 only when using vector.removeAllElements()
[英]Vector IndexOutOfBoundsException
我成功添加了第一個學生,但是當我添加第二個學生時,我得到了
線程“ 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)
代碼段
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);
}
修改為
public Student UseArray(int x){ \\ Error here line 58
if(collection.size() > x)
return collection.get(x);
return null;
}
容量和大小之間有區別。 Capacity返回由Vector
創建的,用於保存當前元素和傳入元素的數組的長度。 而size是已經放入向量中的元素數。 話雖如此,當檢查元素是否存在時,不使用容量使用大小,如下所示:
public int getlengthh(){
return collection.size();
}
即使capacity
大於index
仍然會添加拋出異常。 看這里
像Vector
這樣的集合類的全部要點是,您不需要像數組那樣手動索引它們。 您也不需要維護count變量-當您想知道自己有多少學生時,只需在Vector上調用size()
即可。 現在,除非需要Vector的線程安全性,否則我將改用ArrayList,但它們都是List的實現,這意味着您需要做的就是調用add(Student)
。
在繼續之前,我會仔細看一下Java Collections Trail 。
另外,在風格上,請清理源格式。 縮進不一致會使得很難檢查代碼中的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.