如何将包含集合的对象复制为字段

时间:2013-06-15 11:29:22

标签: java object collections copy

考虑以下代码:

public class Bid {

private double pe;

private List<ResChar> resourceList;


protected Map<Integer,Integer>scheduleOfSeller ;

public Map<Integer, Integer> getScheduleOfSeller() {
    return scheduleOfSeller;
}

public void setScheduleOfSeller(Map<Integer, Integer> scheduleOfSeller) {
    this.scheduleOfSeller = scheduleOfSeller;
}


private int bidId;

public int getBidId() {
    return bidId;
}

public void setBidId(int bidId) {
    this.bidId = bidId;
}

public double getPe() {
    return pe;
}

public void setPe(double pe) {
    this.pe = pe;
}

public List<ResChar> getResourceList() {
    return resourceList;
}

public void setResourceList(List<ResChar> resourceList) {
    this.resourceList = resourceList;
}


public Bid(int bidId,double pe, List<ResChar> resourceList){
    setBidId(bidId);
    setPe(pe);
    setResourceList(resourceList);
    this.scheduleOfSeller = new HashMap<Integer,Integer>();
}

}

我想像这样制作出价的复制构造函数:

public class BidCopy{

public Bid bid;

public BidCopy(Bid bidBuyer){
    List<ResChar> resList = new LinkedList<ResChar>(); 
    for (ResChar elt : bidBuyer.getResourceList()){
        ResCharCopy eltCopy = new ResCharCopy(elt);
        resList.add(eltCopy.elt);
    }
    this.bid = bidBuyer;
    this.bid.setResourceList(resList);
}

}

我知道制作此类副本的唯一解决方案如下:

public class BidCopy{

public Bid copy;

public BidCopy(Bid bid){
    List<ResChar> resList = new LinkedList<ResChar>(); 
    for (ResChar elt : bid.getResourceList()){
        ResCharCopy eltCopy = new ResCharCopy(elt);
        resList.add(eltCopy.elt);
    }
    this.copy = new Bid(bid.getBidId(), bid.getPe(), resList);
}

}

所以我想知道是否有其他解决方案可以更有效地制作“出价”对象的副本?

2 个答案:

答案 0 :(得分:0)

没有。尽管某些集合具有“复制构造函数”,但这些构造函数将复制元素的引用,它们不会为您创建新元素。

然而,您可以通过将初始列表的大小提交给构造函数来“优化”列表创建本身:

List<X> newList = new LinkedList<X>(oldList.size());

答案 1 :(得分:0)

我建议您为Bid对象制作一个复制构造函数(而不是复制的特定类),Bid是由其字段而不是方法构成的,如下所示:

public class Bid {
int ID;
String description;
Object bidStuff;

// ...as before

public Bid(Bid bid) {
    this.ID = bid.ID;
    this.description = bid.description;
    this.bidStuff = bid.bidStuff;
}

public static void main(String[] args) {
    List<Bid> original = new ArrayList<>();
    // ..populate it
    List<Bid> copy = new ArrayList<>(original.size());

    for (Bid b : original) {
        copy.add(new Bid(b));
    }
}
}

如果您不希望其他人混淆制作多个出价副本,您甚至可以使复制构造函数受到保护或受到程序包保护。