Creating an Arraylist of Objects

前端 未结 3 2024
时光取名叫无心
时光取名叫无心 2020-11-27 16:08

How do I fill an ArrayList with objects, with each object inside being different?

3条回答
  •  死守一世寂寞
    2020-11-27 16:44

    If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.

    //here I will create my ArrayList:
    
    ArrayList  rectangles= new ArrayList <>(3); 
    
    int length;
    int width;
    
    for(int index =0; index <3;index++)
    {JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
     length = JOptionPane.showInputDialog("Enter length");
     width = JOptionPane.showInputDialog("Enter width");
    
     //Now I will create my Rectangle and add it to my rectangles ArrayList:
    
     rectangles.add(new Rectangle(length,width));
    
    //This passes the length and width values to the rectangle constructor,
      which will create a new Rectangle and add it to the ArrayList.
    

    }

提交回复
热议问题