首頁 > Java > java教程 > 主體

Java ArrayIndexOutOfBoundsException

王林
發布: 2024-08-30 16:14:33
原創
815 人瀏覽過

當存取超過預定義長度的陣列元素時,會產生 Java ArrayIndexOutOfBoundsException。數組在其確認時進行估計,並且它們本質上是靜態的。當我們定義數組時,元素的數量是固定的,從0開始。例如,如果有10個元素,數組會將第10元素識別為第11 元素,因為第一個元素是第0th元素。一開始,每個程式設計師都認為程式一旦執行,輸出就有保證。但是系統提出的問題會阻止程式在執行時執行,這些問題稱為異常。因此,當執行階段發生 IndexOutOfBoundsException 時,它是由 RuntimeException 類別產生的,而 RuntimeException 類別又是 Main Exception 類別的子類,而這些都衍生自 java.lang 套件。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

建構子

當從 ArrayOutOfBoundsException 實作介面時,就會形成建構子。 ArrayIndexOutOfBoundsException 建構子有 3 種類型,

  • ArrayIndexOutOfBoundsException(): 它建構 ArrayIndexOutOfBoundsException,沒有任何來自控制台的詳細資料。
  • ArrayIndexOutOfBoundsException(int index):索引變數代表另一個不合法的索引,因此它建構了一個ArrayIndexOutOfBoundsException。
  • ArrayIndexOutOfBoundsException(Strings): ArrayIndexOutOfBoundsException 是使用任何正確的訊息建構的。

實作 Java ArrayIndexOutOfBoundsException 的範例

以下是提到的範例:

範例#1

建立 ArrayOutOfBoundsException

代碼:

public class Main
{
public static void main (String[] args)
{
String[] veggies = {"Onion", "Carrot", "Potato", "Tomato", "Cucumber", "Radish"};
for (int i=0; i<=veggies.length; i++)
{
System.out.print (veggies[i] + " ");
}
}
}
登入後複製

輸出:

Java ArrayIndexOutOfBoundsException

在上面的程式中,我們看到名為 veggies 的陣列由 6 個元素組成。一旦for 循環迭代,它會考慮條件I <=veggies.length,這意味著數組會考慮從第0th 位置到第6th 位置的元素,最後,在在最後一次迭代中,值i=6 超出了陣列大小,因此,實作了ArrayoutOfBoundsException。

範例#2

存取負索引的 ArrayOutOfBoundsException

代碼#1

public class Main {
public static void main (String[] args)
{
Integer[] intArray = {5, 7, 9, 11, 13, 15};
System.out.println ( "First element: " + intArray[0]);
System.out.println ( "Last element: " + intArray[-8]);
}
}
登入後複製

輸出:

Java ArrayIndexOutOfBoundsException

在這裡,我們首先聲明一個整數數組,然後我們研究訪問數組中的各個元素。完成後,我們嘗試透過給出命令 intArray[0] 來列印第一個元素。這會識別第 0th 元素,即 5,因此將其列印出來。另一方面,我們也提供了一個指令來將負索引印為-8。因此,系統無法識別該索引,因此在輸出中列印 ArrayOutOfBoundsException。

代碼#2

public class MyClass {
int x;
public MyClass () {
x = 5;
}
public static void main (String[] args) {
MyClass myObj = new MyClass ();
System.out.println (myObj.x);
}
}
登入後複製

輸出:

Java ArrayIndexOutOfBoundsException

如何避免 ArrayIndexOutOfBoundsException?

每個程式設計師在實作陣列索引和元素時都會犯一個錯誤。由於這些原因,發生了 ArrayIndexOutOfBoundsException。我們可以按照以下步驟來避免這些錯誤。

1.增強的 for 迴圈

增強循環會迭代相鄰的記憶體區域(例如陣列),並且僅取得合法索引。從現在開始,當實作增強的 for 迴圈時,我們不必擔心會被誤導或非法索引。

代碼:

class Main {
public static void main (String[] args)
{
String[] fruits = {"Apple", "Mango", "Banana", "Watermelon", "Papaya"};
System.out.println ( "");
for (String strval:fruits)
{
System.out.print (strval + " ");
}
}
}
登入後複製

輸出:

Java ArrayIndexOutOfBoundsException

我們在上面的程式中使用了增強的 for 迴圈來迭代水果數組。首先,我們描述陣列中的 5 個元素,然後實作增強的 for 迴圈。這個循環會迭代直到到達數組末尾,我們不需要單獨定義每個數組。因此,它僅遍歷有效的索引或元素,並最終提供我們正在尋找的內容的準確輸出。因此,我們可以透過利用這個增強的 for 迴圈來避免 ArrayIndexOutOfBoundsException。

2. Proper Start and End Indices

Arrays reliably start with list 0 and not 1. Moreover, the last part in the array can be gotten to using the record ‘arraylength-1’ and not ‘arraylength’. Programming engineers should be mindful while using beyond what many would consider possible and, as such, keep up a key good way from ArrayIndexOutOfBoundsException.

3. Type-Safe Iterator

Type-safe iterators do not toss an exception when they emphasise an assortment and make changes to it as they depict the assortment and roll out the improvements to it.

Code:

import java.util.HashMap;
public class MyClass {
public static void main (String[] args) {
HashMap<String, String> countries = new HashMap<String, String> ();
countries.put ( "India", "Delhi");
countries.put ( "Switzerland", "Bern");
countries.put ( "France", "Paris");
countries.put ( "Belgium", "Brussels");
System.out.println (countries);
}
}
登入後複製

Output:

Java ArrayIndexOutOfBoundsException

Explanation: In the above program, we declare the string of cities and countries and declare that to the HashMap. The system then recognizes this assortment, iterates the code, and finally produces the output without throwing an ArrayIndexOutOfBoundsException.

Conclusion

The ArrayIndexOutOfBoundsException in Java usually occurs when we try to access the elements which are greater than the array length. These exceptions can be avoided by using enhanced for loops or proper indices. There are also exceptions called NullPointerExceptions that are not checked and go beyond RuntimeException; it does not urge the software engineer to utilize the catch square to deal with it. Therefore, we should keep in mind that we should not go beyond array limits and also avoid NegativeArraySizeException.

以上是Java ArrayIndexOutOfBoundsException的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!