Home > Software design >  copy list to another using java
copy list to another using java

Time:11-20

I have two lists in java, entered into two classes

first class. :

public class House implements Entity {

    float length;
    float width;

//setters and getters

Second class. :

public class HousesWithTotal implements Entity {


    private List<house> houses;
    private float totalLength;
    private float totalWidth;

//setters and getters

}

in main, I create list of house, and entered data on it, then I need to copy it to HousesWithTotal object list of houses in attribute, how can I do it ?

CodePudding user response:

I would reccomend to encapsulate logic in the classes.

  • Make classes immutable
  • Calculate of the totalLength and totalWidth should be in the HouseWithTotal class.
@Getter
@RequiredArgsConstructor
public final class House {

    private final double length;
    private final double width;
}

@Getter
public final class HousesWithTotal {

    private final List<House> houses = new ArrayList<>();
    private double totalLength;
    private double totalWidth;

    public void addHouse(House house) {
        houses.add(house);
        totalLength  = house.getLength();
        totalWidth  = house.getWidth();
    }

}

CodePudding user response:

Create a new ArrayList and use constructor or addAll method with the source list.

  • Related