在java中重用变量的问题

时间:2011-07-15 23:10:31

标签: java reference arraylist reusability deep-copy

我在java中引用赋值时遇到了一些问题 让我解释一下:在我的代码中,我正在使用一个BooleanWrap的ArrayList(一个自制的boolean类),它稍后将被指定为HashMap中的一个值(有一个for循环,用于更新此ArrayList的值,直到条件已经过验证) 像这样:

 ArrayList<BooleanWrap> temp=new ArrayList <BooleanWrap>(48);

 //cycle: operations to fill the ArrayList, then a condition is satisfied

 hashMap.put(index, temp);

之后,我必须重用temp变量,所以我需要重新初始化它。我按照以下说明进行操作:

for(BooleanWrap bool: temp){
    bool.set(false);
  }

出现了我的问题:将temp指定为hashMap的值只会保存变量的引用,而不是实际值。
因此,重新初始化temp也会导致hashmap内部的更新(在这种情况下,将所有内容都设置为false) 现在,我认为即使使用clone()方法,我也应该获得相同的结果(因为它会生成ArrayList的浅表副本)。
有没有办法在我的循环中重用相同的变量temp,而不是稍后将它的引用分配给hashmap?
实际上我可以用一种方法来创建一个arraylist的深层副本:

public static ArrayList<BooleanWrap> deepcopy(ArrayList<BooleanWrap> original){

  ArrayList<BooleanWrap> copy=new ArrayList<BooleanWrap>(48);
  for(BooleanWrap bool: original)
      copy.add(new BooleanWrap (bool.get()));

  return copy;

}

但我需要内联完成的东西,没有任何其他方法,并且尽可能短。

任何建议/建议/侮辱?

3 个答案:

答案 0 :(得分:2)

关于变量的问题 。它是关于对象突变的。

所以根据需要创建一个新对象。 “问题”是存储在HashMap中的原始对象 正在变异

但是,避免重复使用变量可以(通常是这样)使代码更易于维护和理解。

快乐的编码。

答案 1 :(得分:1)

  

之后,我必须重用temp变量,所以我需要   重新初始化它。我按照以下说明进行操作:       for(BooleanWrap bool:temp)        {bool.set(false); }

这不会重新初始化临时变量。这会重新初始化临时变量的内容。重新初始化代码看起来像的临时变量

ArrayList<BooleanWrap> temp=new ArrayList <BooleanWrap>(48); 
//cycle: operations to fill the ArrayList, then a condition is satisfied 

hashMap.put(index, temp);

//After that, I have to reuse the temp variable, so I need to reinitialize it. 
// I do it with the following instructions:

temp = new ArrayList <BooleanWrap>(48); 
//cycle: operations to fill the ArrayList

答案 2 :(得分:1)

使用BooleanWRap是非常低效的,即使布尔也效率低。

相反,我建议您使用BitSet。

BitSet temp = new BitSet(48);

//cycle: operations to fill the ArrayList, then a condition is satisfied

hashMap.put(index, temp);

// to create a new BitSet...
temp = new BitSet(48);