从Java ArrayList打印空值

时间:2016-05-24 00:05:55

标签: java arraylist

我正在尝试将null添加到ArrayList,因为它是整数类型。但我得到了NullPointerException

null添加到ArrayList是成功的,但在打印时会引发异常。

请告诉我如何解决此问题。

import java.util.Enumeration;

public enum Car {
     lamborghini(123),tata(2),audi(50),fiat(15),honda(12);
       private int price;
       Car(int p) {
          price = p;
       }
       int getPrice() {
          return price;
       } 
    }



import java.util.ArrayList;

public class Main {
       public static void main(String args[]){
          System.out.println("All car prices:");
          for (Car c : Car.values())
          System.out.println(c + " costs " 
          + c.getPrice() + " thousand dollars.");

         ArrayList<Integer> al = new ArrayList();

         al.add(null);

         for (Car p : Car.values())
             al.add(p.getPrice());

         System.out.println("Size: "+al.size());
      // Loop through elements.
        for (int i = 0; i < al.size(); i++) {
            **int value = al.get(i);**
            System.out.println("Element: " + value);
        }

        //  switch (c)
       }
    }

0 个答案:

没有答案