【发布时间】:2013-09-11 03:01:26
【问题描述】:
我想复制一个包含以下结构的Vector,对我来说重要的是在我修改复制的结构时保持原始Vector 完整:
public class objet_poid_n {
public int Num;
public double Poid;
}
假设我们有:
Vector original = new Vector();
original = filled((Vector) original); // function fills original with many objet_poid_n elements
Vector destination = new Vector();
我试过了:
destination = original ;
和
destination = original.clone();
和
destination.setSize(original.size());
Collections.copy(destination,original);
和
destination.addAll((Vector) original);
和
destination.copyInto((Vector) original);
不幸的是,我使用的所有这些方法总是给我同样的问题! 无论我修改目的地!原来的也改了!!!!!! 请有任何想法!这让我疯狂 !我不明白为什么!现在卡住了 3 天
Vector copy=new Vector((Vector) allPopulation.get(0));
for(int j=0;j<100;j++){
System.out.println("--------------------iteration num :"+(j+1)+"----------------------");
System.out.println("sol 1 ------->");
affiche_resultat((Vector) allPopulation.get(0)); \\ affiche_result to print the containing of the vector just for test
System.out.println("Copy -------->");
affiche_resultat(copy);
Vector muted = new Vector();
muted = mutation(copy);
System.out.println("Mutated ----------->");
affiche_resultat(muted);
System.out.println();}
}
变异函数如下..:
private Vector mutation(Vector son1){
Vector topac = new Vector(); // à remplir par les objet qu'on va supprimer
// dégager les null
Vector son = new Vector(son1);
son.removeAll(Collections.singleton(null));
int j=0,i=0;
boolean remove = (Math.random() > 0.3) ; // probabilité d'avoir true = 0.7
for(i=0;i<son.size();i++){
remove = (Math.random() > 0.3);
System.out.println(" remove ="+remove);
if((remove == true) && (son.get(i) != null)){
Capaciter_n_objet bin =(Capaciter_n_objet) son.get(i);
Vector objetlist=bin.n_objet;
for(j=0;j<objetlist.size();j++)
{
int del =(int) Integer.parseInt(""+objetlist.get(j));
topac.add(new Integer(del));
}
topac.removeAll(Collections.singleton(null));
//son.removeElementAt(i);
son.setElementAt(null, i);
}
}
son.removeAll(Collections.singleton(null));
topac.removeAll(Collections.singleton(null));
Collection noDup = new LinkedHashSet(topac); //remove duplications
topac.clear();
topac.addAll(noDup);
correctionmutation(son,topac);
return son;
}
【问题讨论】:
-
1.不要使用raw types。 2. Don't use
Vector- 改用ArrayList之类的东西。 -
现在我正在修复我的项目程序中的最后一个点,我从一个月开始就开始了它..我用 Vectors 开始它..不,除了我不这样做,我不能后退并改变以处理 ArrayList不知道如何使用它们..
-
您应该发布修改元素的代码,以演示实际问题 - 因为不清楚您的意思是“保持原件完好无损”以及您在副本上所做的“修改”
-
您应该使用
List类型的引用,因此除了实际实例化实现的行之外,实现与所有代码无关。这样,您可以在必要时轻松无缝地替换实现(例如,在适当的情况下使用 LinkedList 代替)。 -
@JohnGaughan 我真的需要一个解决方案来获得可编辑的副本,而无需修改原始文件或弄乱它的数据..
标签: java netbeans data-structures vector copy