ArrayList的使用
储存随机数字
题目要求
代码实现
import java.util.ArrayList;
import java.util.Random;
public class demo08 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 6; i++) {
int num = r.nextInt(33) + 1;
list.add(num);
}
System.out.println(list);
}
}
储存自定义对象
题目要求
代码实现
import java.util.ArrayList;
public class demo01 {
public static void main(String[] args) {
Student one = new Student("蔡徐坤", 19);
Student two = new Student("王一博", 20);
Student three = new Student("易烊千玺", 23);
Student four = new Student("王源", 21);
ArrayList<Student> list = new ArrayList<>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
System.out.println("姓名:" + stu.getName() + ",年龄:" + stu.getAge());
}
}
}
集合作为方法参数
题目要求
代码实现
import java.util.ArrayList;
public class demo02 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("易烊千玺");
list.add("王源");
list.add("王俊凯");
list.add("蔡徐坤");
list.add("王一博");
System.out.println(list);
printArrayList(list);
}
public static void printArrayList(ArrayList<String> list) {
System.out.print("{");
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (i != 0) {
System.out.print("@" + s);
} else {
System.out.print(s);
}
}
System.out.println("}");
}
}
集合作为方法的返回值
题目要求
产生一个装有20个随机数的大集合,调用方法产生一个是由大集合里面的偶数所构成的小集合
代码示例
import java.util.ArrayList;
import java.util.Random;
public class demo03 {
public static void main(String[] args) {
ArrayList<Integer> bigList = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 20; i++) {
int num = r.nextInt(100) + 1;
bigList.add(num);
}
System.out.println(bigList);
ArrayList <Integer> smallList =getSmall(bigList);
System.out.println("该集合有"+smallList.size()+"个偶数元素");
System.out.println(smallList);
}
public static ArrayList<Integer> getSmall(ArrayList<Integer> bigList) {
ArrayList<Integer> smallList = new ArrayList<>();
for (int i = 0; i < bigList.size(); i++) {
int num = bigList.get(i);
if (num % 2 == 0) {
smallList.add(num);
}
}
return smallList;
}
}
标签:ArrayList,list,System,add,使用,new,out
From: https://www.cnblogs.com/harper886/p/17321269.html