生成6個1~33之間的隨機整數,添加到集合,並遍歷
public class ArrayListDemo1 { public static void main(String[] args) { // 創建Random 對象 Random random = new Random(); // 創建ArrayList 對象 ArrayList<Integer> list = new ArrayList<>(); // 添加隨機數到集合 for (int i = 0; i < 6; i++) { int r = random.nextInt(33) + 1; list.add(r); } // 遍歷集合輸出 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
自定義4個學生對象,添加到集合,並遍歷
public class TestStudent { public static void main(String[] args) { //創建集合對象 ArrayList<Student> list = new ArrayList<Student>(); //創建學生對象 Student s1 = new Student("趙麗穎",18); Student s2 = new Student("唐嫣",20); Student s3 = new Student("景甜",25); Student s4 = new Student("柳岩",19); //把學生對象作為元素添加到集合中 list.add(s1); list.add(s2); list.add(s3); list.add(s4); //遍歷集合 for(int x = 0; x < list.size(); x++) { Student s = list.get(x); System.out.println(s.getName()+"‐‐‐"+s.getAge()); } } }