创建新对象后,ArrayList为空

时间:2017-10-18 13:41:33

标签: java android arraylist

我试图在MainActivity.java中使用for循环创建虚拟对象的ArrayList。这似乎工作正常,因为我得到了我创建的每个对象的对象引用:

for(int i=0; i < 10; i++){
  new TaskObjects("Title " + i, "Category " + i, "Description " + i, i + 10);
  Log.d("For Loop", "" + i);
}

我在构造函数中有一个log(this.toString()),它返回10次,如下所示:

D / ARRAY:com.mail.app_appname.TaskObjects@af4fd26(每个ID不同)

TaskObjects类:

public class TaskObjects {
  private String title;
  private String category;
  private String description;
  private int taskPosterID;
  private ArrayList<TaskObjects> tasksArray = new ArrayList<>();

  public TaskObjects(String title, String category, String description, int taskPosterID){
    this.title = title;
    this.category = category;
    this.description = description;
    this.taskPosterID = taskPosterID;
    tasksArray.add(this);
    Log.d("ARRAY",this.toString());
  }
  //getters and setters
}

但是当我尝试返回数组的大小时,它返回0.

2 个答案:

答案 0 :(得分:1)

你必须使tasksArray静态。否则,TaskObjects的每个实例都会创建一个新的(=空)taskArray

private static ArrayList<TaskObjects> tasksArray = new ArrayList<>();

答案 1 :(得分:0)

public class TaskObjects {
  private String title;
  private String category;
  private String description;
  private int taskPosterID;


  public TaskObjects(String title, String category, String description, int taskPosterID){
    this.title = title;
    this.category = category;
    this.description = description;
    this.taskPosterID = taskPosterID;


  }
  //getters and setters
}

MainActivity.java

private ArrayList<TaskObjects> tasksArray = new ArrayList<>();


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_activity);

for(int i=0; i < 10; i++){
TaskObjects task=  new TaskObjects("Title " + i, "Category " + i, "Description " + i, i + 10);
tasksArray.add(task);
  Log.d("For Loop", "" + i);
}

}