【问题标题】:How can I give an Order in for loop when Creating Objects?创建对象时如何在 for 循环中下订单?
【发布时间】:2019-12-23 06:58:36
【问题描述】:

我想创建具有学生 1、学生 2、学生 3 等顺序的学生对象。 然后我想将我的对象添加到 ArrayList 中。所以我尝试了这个:

ArrayList<Student> students = new ArrayList<Student>();
Student student;
for (int i=0; i<20; i++) {
    student=new Student();
    students.add(student);
}

但是,我认为上面的代码没有给出命令。它只创建了 20 个学生对象。 我想知道如何使用 for 循环创建 20 个学生对象并对这些对象进行排序。

【问题讨论】:

  • 您创建的这些对象没有内容 - 您应该如何对其进行排序?
  • 在学生班我有一个变量 id
  • 根据定义,列表始终保持元素的顺序。这不仅适用于 ArrayList
  • 在学生类中我有一个变量 id - 不要让我们猜测你在做什么,请显示代码以便我们理解。 id 什么时候设置?
  • @lczapski - ArrayList 是一个列表 - add 也将添加到列表的末尾

标签: java android for-loop arraylist


【解决方案1】:

下面试试

class Student{
  private int id;
    //remaining member variables 

    Student(int id){
        this.id = id;
    }



}



ArrayList<Student> students=new ArrayList<Student>();
Student student;
for(int  i=0;i<20;i++) {
    student=new Student(i+1);
    students.add(student);
}

//This will print student details;
for(int z=0;z<student.size();z++){
System.out.println("Student "+student[i].getId());
}

【讨论】:

    【解决方案2】:

    请参考添加函数的java文档-

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    

    这意味着秩序将被保留。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 2012-12-27
      相关资源
      最近更新 更多