Zum Inhalt springen
View in the app

A better way to browse. Learn more.

Fachinformatiker.de

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

java.lang.NullPointerException bei array in arraylist

Empfohlene Antworten

Veröffentlicht

Hallo,

ich habe ein eine Arrayliste ein Array eingebunden



ArrayList arrlist = new ArrayList();


String[] element = null; 


for(int i = 1; i <= 1000; i++){


    for(int u = 1; u <= 8; u++){


        element = new String[8];


        schreib = String.valueOf(i) + "A" + String.valueOf(u);


        element[u-1] = schreib;


    }


    arrlist.add(element);


}


und möchte die Werte aus der Arraylist, als array element in ein Array testarr schreiben


String[][] testarr;


testarr = new String[arrlist.size()][8];


try{



    for(int c = 1; c < arrlist.size(); c++) { 


        testarr[c-1] = ((String[])arrlist.get(c-1)); 


    } 


    System.out.println(testarr[155][7].toString()); 


}catch (Exception e){


    System.out.println(e.toString());


}


wenn ich versuche, den wert im letzten Feld des Array zu lesen

klappt es

System.out.println(testarr[155][7].toString());

wenn ich versuche den Wert in einem der vorherigen Felder zu lesen

bekomme ich eine

java.lang.NullPointerException

bei

System.out.println(testarr[155][5].toString());

Weiss jemand, wieso ich dann eine java.lang.NullPointerException

bekomme?

LG Kai

Bearbeitet von Kaihai

Du legst deine Arrays von 8 Strings jeweils 8 Mal an. Dabei wirfst du jedesmal das vorherige Array weg. Es bleibt nur das letzte, bei dem dann eben nur das 8. Element tatsächlich ein Stringobjekt enthält.

Sprich: Es ist keine gute Idee, das Array in der inneren Schleife zu erzeugen.

Manchmal sieht man den Wald vor lauter Bäumen nicht

Es funktioniert

Danke

LG Kai

Erstelle ein Konto oder melde dich an, um einen Kommentar zu schreiben.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.