Home > Enterprise >  Java List auto create and add
Java List auto create and add

Time:05-17

Is it possible to replace this:

    if (archiveUnitEntity.getArchiveCaseEntityList() == null) {
      archiveUnitEntity.setArchiveCaseEntityList(new ArrayList<ArchiveCaseEntity>());
    }
    
    archiveUnitEntity.getArchiveCaseEntityList().add(archiveCaseEntity);

This something like that:

ifListNullCreate(archiveUnitEntity.getArchiveCaseEntityList()).Add(archiveCaseEntity);

CodePudding user response:

If you can change the method getArchiveCaseEntityList() then you could add that null check into the getter and update it there (or create another method if you need it to be null in some cases). If not, then you could create the method you want wherever you want/need.

But I don't think there is a built-in method to do that.

CodePudding user response:

Here's one possible solution.

In the ArchiveUnitEntity class, declare the list like this, so that it's not null on creation.

private List<ArchiveCaseEntity> archiveCaseEntityList = new ArrayList<>();

You might also want to change the setter for that field, so that it can't get set to null.

public void setArchiveCaseEntityList(ArchiveCaseEntityList archiveCaseEntityList) {
    this.archiveCaseEntityList = archiveCaseEntityList == null ? new ArrayList<ArchiveCaseEntity>() : archiveCaseEntityList;
}

CodePudding user response:

It's better to initialize your archiveCaseEntityList attribute during the creation of the instance of archiveUnitEntity. Avoiding null object can simplify a lot of things :)

Directly when you declare your attribute :

private List<ArchiveCaseEntity> archiveCaseEntityList = new ArrayList<>();

or in constructor :

public ArchiveUnitEntity(){
   this.archiveCaseEntityList = new ArrayList<>();
}

And finally, you could build a new method to manage ArchiveCaseEntity addition :

public void addArchiveCaseEntity(ArchiveCaseEntity entity){
   this.archiveCaseEntityList.add(entity);
}
  • Related