1

I am trying to create an array of HashMaps within a class and then retrieve a hashmap from the array for calculation purposes. Here is my code:

HashMap<String, Integer>[] boardPopulation= (HashMap<String, Integer>[]) new HashMap[populationSize];
    for(int i=0; i < populationSize; i++){
        generateQueens();
        boardPopulation[i] = queenMap;
    }
    for(int i=0; i < populationSize; i++){
        queenMap = boardPopulation[i];
        printBoard();
    }

When I compile I get two issues:

  1. Board.java uses unchecked or unsafe operations, recompile with -Xlint:unchecked.
  2. When I compile with "Xlint:unchecked" I get

Warning: [unchecked] unchecked cast HashMap[] boardPop.......(same as line 1 of above code)

required: HashMap[] found: HashMap[]

Please help me ! :D

Ideally I would like to not have to use Xlint unchecked, but ultimately I really just need to be able to retrive a HashMap from the list and assign it to queenMap so I can do calculations within the class.

Thankyou

  • Try `@SuppressWarnings("unchecked")` before your declaration of `boardPopulation` – Stefan Warminski Apr 03 '17 at 06:13
  • Marking as duplicate. Answer is here: http://stackoverflow.com/a/14917529/2390219 – kukis Apr 03 '17 at 06:19
  • Possible duplicate of ["Cannot create generic array of .." - how to create an Array of Map?](http://stackoverflow.com/questions/14917375/cannot-create-generic-array-of-how-to-create-an-array-of-mapstring-obje) – kukis Apr 03 '17 at 06:19

1 Answers1

2

Sorry for answering a slightly different question but if an array isn't essential, have you tried using a generic list:

List<Map<String, Integer>> boardPopulations = new ArrayList<>();
boardPopulations.add(new HashMap<>()); 
muzzlator
  • 742
  • 4
  • 10
  • 1
    I literally just found something very similar and I think it is doing what I need now. Code: < List> boardPopulation = new ArrayList>(); for(int i=0; i < populationSize; i++){ generateQueens(); boardPopulation.add(i, queenMap); – Dylan Atkinson Apr 03 '17 at 06:25
  • Cool, looks better. If you're using java 7 I think should be able to just do List> boardPopulation = new ArrayList<>(), the type of the ArrayList constructor should be inferred from the declaration of boardPopulation as a List> – muzzlator Apr 03 '17 at 06:31
  • Using Java 8. I now have a new issue. Is there any chance I could ask you to private chat to go into more detail? I'm asking because the new issue is less related to this question and more related to understanding the problem I am solving. – Dylan Atkinson Apr 03 '17 at 06:34
  • Go ahead, I don't know how to start one but I assume you do – muzzlator Apr 03 '17 at 06:35