JAVA 对象数组和空指针异常
生活随笔
收集整理的這篇文章主要介紹了
JAVA 对象数组和空指针异常
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
對象數(shù)組同基本類型數(shù)組相同
Test_10 [] students; Test_10 students []; int [] array; int array [];此時創(chuàng)建的數(shù)組,并沒有分配到內(nèi)存空間
內(nèi)存的分配有兩種,一種是靜態(tài)分配,另一種時動態(tài)分配
students [0] = new Test_10("aaaa", 1); students [1] = new Test_10("bbbb", 2); students [2] = new Test_10("cccc", 3); students [3] = new Test_10("dddd", 4); students [4] = new Test_10("eeee", 5); Test_10 [] students = { new Test_10("aaaa", 1),new Test_10("bbbb", 2),new Test_10("cccc", 3),new Test_10("dddd", 4),new Test_10("eeee", 5),這樣一個個添加未免效率太低了,并且大多時候,我們并不確定需要有多少記錄去存儲,如果每次都要改,也太麻煩了
因此想到基本類型數(shù)組那樣去賦值,但是那樣寫編譯器總是拋出空引用(空指針)異常
空指針異常:空指針就是空引用,java空指針異常就是引用本身為空,卻調(diào)用了方法,這個時候就會出現(xiàn)空指針異常。可以理解,成員變量和方法是屬于對象的(除去靜態(tài)),在對象中才存在相對應(yīng)的成員變量和方法,然后通過對象去調(diào)用這些成員變量和方法。對于空指針來說,它不指向任何對象,也就沒有所謂的成員變量和方法,這個時候用它去調(diào)用某些屬性和方法,自然就會出現(xiàn)空指針異常了。
Scanner sc = new Scanner(System.in); Test_10 [] students = new Test_10[5]; for(int i = 0; i < 5; i++) {String name = sc.next();int num = sc.nextInt();students[i] = new Test_10(name,num); }每次賦值之前,都通過構(gòu)造器創(chuàng)建對象,因此避免了空指針的出現(xiàn)
完整代碼
import java.util.Scanner;public class Test_10 {public String name;public int num;public Test_10(String name, int num) {this.name = name;this.num = num;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);Test_10 [] students = new Test_10[5];for(int i = 0; i < 5; i++) {String name = sc.next();int num = sc.nextInt();students[i] = new Test_10(name,num);}for(Test_10 t : students) {System.out.println(t.name + " " + t.num);}sc.close();}}?
總結(jié)
以上是生活随笔為你收集整理的JAVA 对象数组和空指针异常的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: strtok.c
- 下一篇: 这份交互稿模板,可以让你的设计稿非常规范