ArrayList集合储存基本数据类型


如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。

基本类型 包装类(引用类型,包装类都位于java.lang包下)
byte Byte
short Short
int Integer 【特殊】
long Long
float Float
double Double
char Character 【特殊】
boolean Boolean

从JDK 1.5+开始,支持自动装箱、自动拆箱。

自动装箱:基本类型 --> 包装类型
自动拆箱:包装类型 --> 基本类型
 1 import java.util.ArrayList;
 2 
 3 public class Demo05ArrayListBasic {
 4 
 5     public static void main(String[] args) {
 6         ArrayList<String> listA = new ArrayList<>();
 7         // 错误写法!泛型只能是引用类型,不能是基本类型
 8 //        ArrayList<int> listB = new ArrayList<>();
 9 
10         ArrayList<Integer> listC = new ArrayList<>();
11         listC.add(100);
12         listC.add(200);
13         System.out.println(listC); // [100, 200]
14 
15         int num = listC.get(1);
16         System.out.println("第1号元素是:" + num);
17     }
18 
19 }

 

posted @ 2020-10-14 10:13  Oooooooa  阅读(512)  评论(0)    收藏  举报