【问题标题】:Creating an Arraylist of Objects创建对象的 Arraylist
【发布时间】:2011-04-28 07:23:33
【问题描述】:

如何用对象填充 ArrayList,其中每个对象都不同?

【问题讨论】:

标签: java android object arraylist


【解决方案1】:
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

【讨论】:

    【解决方案2】:

    如何创建对象的 Arraylist。

    创建一个数组来存储对象:

    ArrayList<MyObject> list = new ArrayList<MyObject>();
    

    一步到位:

    list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 
    

    MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
    list.add(myObject); // Adding it to the list.
    

    【讨论】:

      【解决方案3】:

      如果您想允许用户将一堆新的 MyObjects 添加到列表中,您可以使用 for 循环来实现: 假设我正在创建一个 Rectangle 对象的 ArrayList,每个 Rectangle 都有两个参数 - 长度和宽度。

      //here I will create my ArrayList:
      
      ArrayList <Rectangle> 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.
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-08
        • 2013-09-26
        • 2020-03-21
        • 2019-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多