我正在尝试将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)
}
}