簡體   English   中英

錯誤:10 [1.1、1.2、1.3、1.4、1.5、1.6] 線程“主”java.lang.ArrayIndexOutOfBoundsException 中的異常:數組索引超出范圍:0 處為 ja

[英]Error: 10 [1.1, 1.2, 1.3, 1.4, 1.5, 1.6] Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0 at ja

package basics;

import java.util.*;
public class VectorDemo {

public static void main(String[] args) {
int size = 5;
int incr = 5;
String st[] = {"Spring Roll", "Pizza", "Pasta"};
Vector<String> v1 = new Vector<String>(); //default size = 10
Vector<Integer> v2 = new Vector<Integer>(size); //constructor
Vector<Double> v3 = new Vector<Double>(size, incr); //constructor
v1.add("Hello");
v1.add("My");
v1.add("Dear");
v1.add("friend");
v1.add("shashank");
v1.add("bye");
//System.out.println(v1);
List<String> l1 = new Vector<String>(Arrays.asList(st)); //we can create Vector using this method.
//System.out.println(l1);
//Default vector
Vector vd = new Vector(); // object creation of Vector class.
vd.add(23);
vd.add("Any string ");
//System.out.println(vd);
//System.out.println(v3.capacity());
v3.add(1.1); v3.add(1.2); v3.add(1.3); v3.add(1.4); v3.add(1.5); v3.add(1.6); //
System.out.println(v3.capacity());
System.out.println(v3);
//v1.get(size);
//v1.lastElement();
//v1.sort(null);
//v1.remove(0);
//v1.clear();

//System.out.println(v1.lastElement());

v3.get(size);
v3.lastElement();
v3.sort(null);
v3.remove(0);
v3.clear();

System.out.println(v3.remove(0));
System.out.println(v3);


}
}

I am getting the output as 10 [1.1, 1.2, 1.3, 1.4, 1.5, 1.6] and error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0 at java.base/java.util .Vector.remove(Vector.java:844) 在 OOPSiFun/basics.VectorDemo.main(VectorDemo.java:45)

問題出在導致ArrayIndexOutOfBoundsExceptionVector v3中,基本上拋出此異常以指示已使用非法索引訪問了數組。


您已經創建了一個完全沒問題的向量實例

Vector<Double> v3 = new Vector<Double>(size, incr); //constructor

你在那里添加了一些元素,。

 v3.add(1.1); v3.add(1.2); v3.add(1.3); v3.add(1.4); v3.add(1.5); v3.add(1.6); //

你想獲得Vector的大小並刪除索引 0 中的元素,我們現在很好。

v3.get(size);
v3.remove(0);

問題來了

使用此行v3.clear()您已刪除Vector中的所有元素,因此Vector中基本上沒有元素,因此如果您嘗試訪問空數組中的元素索引,它將像您的情況一樣向您拋出ArrayIndexOutOfBoundsException您嘗試使用System.out.println(v3.remove(0));訪問索引 0 中的元素 ,但該索引中沒有元素,因為 Vector 為空。


因此,如果您仍想使用 clear 方法,請像這樣使用它

        v3.get(size);
        v3.lastElement();
//       v3.sort(null);
        v3.remove(0);
       
        System.out.println(v3.remove(0));
        System.out.println(v3);

        v3.clear();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM