令人费解的地图行为

问题描述:

我正在尝试构建一个学校作业的程序,该程序可生成传递闭包给定的一组函数依赖关系。我正在使用JAVA。为了使它识别字符串子集,我必须构建一个名为Attribute的类,由char和布尔字段组成(以帮助进一步识别包含字符序列的字符串令人费解的地图行为

然后,我有一个名为FunctionalDependency的类,它只具有两个映射 <Integer, Attribute>。 第一图表示左手和属性的第二右手。

最后我的主要程序,它实际calculationhas地图的Integer,FunctionalDependency一个,这表示该用户希望将依赖集输入。我的问题位于方法insertFD(),更具体地说在第一个for{}块。在for块中,映射似乎具有我想要的值,在它之外(意思是在最后一次调用循环之后),它会复制到映射的最后一个字符的地图的所有位置,从而破坏进一步的计算。

/*The method for inserting a new FD*/ 
    public void insertFD() throws IOException{ 
     Map<Integer, Attribute > tempMapLeft= new HashMap<Integer,Attribute>(); 
     Map<Integer, Attribute > tempMapRight= new HashMap<Integer,Attribute>(); 
     Attribute tempAttrLeft = new Attribute(); 
     Attribute tempAttrRight = new Attribute(); 
     FunctionalDependency tempDependency=new FunctionalDependency(); 


     String tempString; 
     BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); 
     System.out.println("Please give the string for the left hand:"); 
     System.out.flush(); 
     tempString=stdin.readLine(); 
     tempString.toUpperCase(); 
     System.out.println("Your input is "+tempString); 


     for(int j=0;j<tempString.length();j++) 
     { 
      System.out.println("for j="+j+"letter is "+(tempString.toCharArray()[j])); 
      tempAttrLeft.setTheCharacter(tempString.toCharArray()[j]); 
      tempAttrLeft.setCheck(true); 
      tempMapLeft.put(j, tempAttrLeft); 
      System.out.println("I just inserted "+ tempAttrLeft.getTheCharacter()); 
      System.out.println("Here is the proof: "+tempMapLeft.get(j).getTheCharacter()); 
     } 
     System.out.println(tempMapLeft.get(0).getTheCharacter()); 
     System.out.println(tempMapLeft.get(1).getTheCharacter()); 
     tempDependency.setLeftHand(tempMapLeft); 
     //fSet.put(number, tempDependency); 
     //fSet.get(number).setLeftHand(tempMapLeft); 

     System.out.flush(); 
     System.out.println("Your left hand is at 0 "+ tempDependency.getLeftHand().get(0).getTheCharacter()); 
     System.out.println("Your left hand is at 1 "+ tempDependency.getLeftHand().get(1).getTheCharacter()); 

我没有任何Java专家,但我看不到我的代码错误,我会很高兴,如果你能帮助我,在此先感谢。

+1

你会得到更有效的帮助,如果你不不要把你的全部代码转储给我们,而是花点时间只提供**相关的**代码。换句话说,仔细检查你的代码,并将其解释为展示问题的*最小*示例。请参阅http://sscce.org。 –

+0

一个无关的提示:你可以省略'System.out.flush()'调用; 'println'会自动刷新流,除非你不想让它失败。 –

+0

谢谢!现在编辑问题! – Damerian

你的问题是,你不断重复使用相同的tempAttrLeft和tempAttrRight在循环的每个过程中。地图中的每个键都指向同一个对象!您需要在循环的每个过程中创建一个新的tempAttrLeft和tempAttrRight。该地图保持对你放入它的对象的引用,它不会“复制”它。因此,当您更改循环的下一个循环中的值时,该映射关键字会与新值相同。

+0

谢谢!我在'for'循环中声明了'tempAttribute',而不是在外面,问题就解决了!谢谢! – Damerian

我不确定什么是预期的和实际的输出。但是,一些事情可以尝试:

  1. 你不会得到大写的tempString.toUpperCase();这是因为对String不可改变的特征。相反:tempString = tempString.toUpperCase();
  2. 当接受右手输入时重新初始化tempString
+0

感谢RC编辑我的文章:-)。下次我会照顾的。 – Gaurav

在你for循环,您使用的是Attribute实例,它是每一个j相同,所以在循环后,每个地图项包含相同Attribute

+0

谢谢!这是确切的问题,现在是固定的! – Damerian