如何把隨機數或者對象添加到ArrayList集合


生成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());
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM