0

Below is my starting code. I have learned a bit on HashMaps, created them and used them. But I am having a problem creating a copy of a HashMap I have built. I can recreate a new one, but the idea is to have some Keys & values of a map built, but from another method. My methods are all public. I have created a private myMap in the Class. But when I try to access myMap in another method, the most I get is an empty {}. Occasionally I get 'null' but I figured out at least how to get from nullto to {}. I just want to be able to .getKey... to get the HashMap data.

Hope this is clear? If not will try to send more.

public class CodonCount {  
   private HashMap<String,Integer> myMap = new HashMap<String,Integer>();

public CodonCount() { 
System.out.println("myMap (beginning of Constructor) = " + myMap);
  }

public HashMap buildCodonMap(int start, String dna) {
 System.out.println("myMap (beginning of buildCodonMap) = " + myMap);       
HashMap<String,Integer> myMap = new HashMap<String,Integer>();
btcomp
  • 1

1 Answers1

1

As you already have myMap declared as a class variable, if you do this

public HashMap buildCodonMap(int start, String dna) {
  System.out.println("myMap (beginning of buildCodonMap) = " + myMap);       
  HashMap<String,Integer> myMap = new HashMap<String,Integer>();
  ....
}

you are re-declaring myMap

try

public HashMap buildCodonMap(int start, String dna) {
   System.out.println("myMap (beginning of buildCodonMap) = " + myMap);     
   myMap = new HashMap<String,Integer>();
   ....
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • Scary, you are brilliant. Now I don't need the myMap = new HashMap because my problem was that I was trying to 'Overdo' something I have to watch myself. (i.e. If you have ever watched the sitcom "The Middle", think of me as Brick) – btcomp Oct 04 '16 at 14:51
  • [REVISED] Scary, you are brilliant. Now I don't need the myMap = new HashMap because my problem was that I was trying to 'Overdo' something I have to watch myself. (i.e. If you have ever watched the sitcom "The Middle", think of me as Brick) public void tester(){ String key = "TCA"; Integer value = myMap.get(key); System.out.println("The codon value is: " + value); } output from the tester: The codon value is: 2 myMap (beginning of buildCodonMap) = {} myMap (after building HashMap in buildCodonMap) = {CGT=1, TCA=2, AGT=1} – btcomp Oct 04 '16 at 15:00
  • If this answer was useful please consider accepting this answer – Scary Wombat Oct 05 '16 at 00:17