1.ArrayList是一个数组列表,提供了相关的添加、删除、修改、遍历等功能。
ArrayList 类提供了很多有用的方法
2.初始化
ArrayList objectName =new ArrayList<>(); //初始化
3.添加元素:用 add () 方法
list.add("哈士奇"); //添加一个元素
4.访问元素:用 get () 方法
String name = list.get(2); //访问第三个元素
5.修改元素:用 set () 方法
arr.set(1, "10"); // 设置第2个元素为10
6.删除元素:remove()
arr.remove("a"); //在数组里删除元素(根据对象删除)
arr.remove(0); //根据下标删除ArrayList的元素
7.获取数组:size()
list.size(); //获取数组的大小
8.遍历
for(int i = 0; i
注意:数组的索引值是从0开始的
“
9.示例:随机不重复点名
public class Dm {
public static void main(String[] args) {
//可以使用Arrays的asList实现序列化一个集合
List list= Arrays.asList("叶枫","饶政","郭汶广","王志刚","时力强",
"柴浩阳","王宁","雷坤恒","张武超","李炳杰","刘传","焦泽国","胡凯",
"贠耀强","齐东豪","袁文涛","孙啸聪","李文彬","孙赛欧","曾毅","付临",
"王文龙","朱海尧","史艳红","赵冉冉","詹梦","苏真娇","张涛","王浩",
"刘发光","王愉茜","牛怡衡","臧照生","梁晓声","孔顺达","田野","宫帅龙",
"高亭","张卓","陈盼盼","杨延欣","李蒙惠","瞿新成","王婧源","刘建豪",
"彭习峰");
//把list作为参数重新构建一个新的ArrayList集合
ArrayList names=new ArrayList<>(list);
Random random=new Random();
Scanner sc=new Scanner(System.in);
while (true){
if(names.size()==0){
System.out.println("已完成所有抽查,结束后请从新开始");
break;
}
System.out.println("确认点名请输入1");
String input =sc.next();
if (input.equals("1")){
int index=random.nextInt(names.size());
System.out.println("本次抽到的同学是:"+names.get(index));
names.remove(index);
}else {
System.out.println("抽查结束");
break;
}
}
}
}
1.基本数据类型所对应的引用数据类型
2.拆箱和装箱
装箱:把基本数据类型转换成包装类型
Integer a3=new Integer(5);
System. out. printLn(a3);
拆箱:把包装类型转换成基本数据类型
int a5=a3.intValue();
System.out.printLn(a5);