Java ArrayIndexOutOfBoundsException

王林
リリース: 2024-08-30 16:14:33
オリジナル
815 人が閲覧しました

Java ArrayIndexOutOfBoundsException は、事前定義された長さを超える配列要素にアクセスすると生成されます。配列は確認時に推定され、本質的には静的です。配列を定義するとき、要素の数は固定されており、0 から始まります。たとえば、要素が 10 個ある場合、配列は 10 番目 の要素を 11 番目 要素は、最初の要素が 0 番目 要素であるためです。最初は、すべてのプログラマは、プログラムが実行されれば、出力は保証されると考えます。ただし、実行時にプログラムの実行を妨げるシステムによって発生する問題があり、これらの問題は例外と呼ばれます。したがって、この IndexOutOfBoundsException が実行時に発生すると、Main Exception クラスのサブクラスである RuntimeException クラスから生成され、これらはすべて java.lang パッケージから派生します。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

コンストラクター

コンストラクターは、インターフェイスが 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 が考慮されます。これは、配列が 0

th 位置から 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] を与えて最初の要素を出力しようとします。これは 0

th 要素 (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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!