0

考虑下面的代码:

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);
}

}

所以我想知道是否有任何其他解决方案可以更有效地复制“投标”对象?

4

2 回答 2

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));
    }
}
}

如果您不想让其他人乱制作多个投标副本,您甚至可以使复制构造函数受到保护或包保护。

于 2013-06-15T11:53:51.427 回答
0

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

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

List<X> newList = new LinkedList<X>(oldList.size());
于 2013-06-15T11:35:19.363 回答