2

我正在使用 HashMap,其中键是字符串,值是对象(信号)。在遍历 Map 时,我可以在将对象的属性之一写入文件之前对其进行编辑吗?

这是我的代码

public void createFile(HashMap<String , Signal> map, final BufferedWriter buffwriter, long totalSize) {
    final Iterator<String> iterator = map.keySet().iterator();
    while(iterator.hasNext()) {
       String messageName = iterator.next();
       Signal signal  = map.get(messageName);
       signal.setBandwidth((signal.getSize()/totalSize)*100);
       csvOutput.write(signal.getSource());
       csvOutput.write(signal.getName());
       csvOutput.write(signal.getComponent());
       csvOutput.write(Integer.toString(signal.getOccurance()));
       csvOutput.write(Integer.toString(signal.getSize()) );
       csvOutput.write(Float.toString(signal.getBandwidth()));
       csvOutput.endRecord();               
    }
 }

信号.java

  public class Signal implements Comparable<Signal>{    
      String name;
      float bandwidth;

      public void setName(String name){
       this.name = name;
   }
      public void setBandwidth(float bandwidth){
       this.bandwidth  = bandwidth;
   }

       public String getName(){
       return this.name;
   }

       public float getBandwidth(){
       return this.bandwidth;
   }
        @Override
   public int compareTo(Signal signal) {
       return 1;
   }

在上面的代码中,我使用messagName 作为映射中每个键的键,我得到它的值尝试设置带宽属性,然后将其写入文件,但它没有更新带宽。

我该怎么做 ?我剩下的唯一选择是删除条目并在迭代时添加另一个具有新值的选项吗?

提前致谢

4

2 回答 2

2

让我猜猜,您的带宽保持为 0?那是因为你计算它的方式。我假设 getSize() 返回一个 int/long,而 totalSize 是一个 int/long。这将导致您的计算结果

(signal.getSize()/totalSize)*100

也是一个 int 。尝试以下操作:

(signal.getSize() / (float) totalSize) * 100

现在其中一个操作数是浮点数,是什么使计算结果也成为浮点数。希望这可以解决您的问题。

另请参见此处

于 2013-09-24T10:26:39.267 回答
0

OK, firstly you CAN modify any object state by reference, so, you got reference to Signal and you can set what do you want (if that object mutable), that one of the reason why I asked to provide code of the class.

I tested your example like next

 Signal signal = new Signal();
    signal.setName("1");
    signal.setBandwidth(23);
    HashMap<String , Signal> map = new HashMap<String , Signal>();
    map.put("1", signal);
    final Iterator<String> iterator = map.keySet().iterator();
    while(iterator.hasNext()) {
      String messageName = iterator.next();
      signal  = map.get(messageName);
      signal.setBandwidth(1000);
      System.out.println(signal.getBandwidth());
    }
  }

and in result I will see 1000.0

BTW try to use EntrySet insted of keySet + get

于 2013-09-24T10:29:30.813 回答