-1

I'm making a call to a separate class method that is expected to return a hashmap with string arrays as values. From within the method, the values are accessible as an array, but when returned to the calling class method, it "becomes" an object and generates the error:

array required, but java.lang.Object found

The calling method:

public HashMap getBranches(){
    HashMap branches = dbMgr.getBranches();
    branches.forEach( (index, branch) -> {
      System.out.println(branch[0]); // This generates the error.
    });
    return(branches);
  }

The method returning the hashmap:

HashMap branches = new HashMap<String, String[]>();
public HashMap getBranches(){

    System.out.println("\n[>] Getting branches...\n");
    DataFormatter formatter = new DataFormatter();
    Sheet sheet = tables.get("tbl_library_branch").getSheetAt(0);
    Iterator rowIter = sheet.rowIterator();

    while( rowIter.hasNext() ) {

      Row row = (Row) rowIter.next();
      Iterator cellIter = row.cellIterator();

      while(cellIter.hasNext()){
          String primaryKey = formatter.formatCellValue( (Cell) cellIter.next());
          String name = formatter.formatCellValue( (Cell) cellIter.next());
          String address = formatter.formatCellValue( (Cell) cellIter.next());
          String[] branch = new String[2];
          branch[0] = name;
          branch[1] = address;
          branches.put( primaryKey, branch );
      }
    }    
    return branches;

I've tried using ArrayLists as well, but then I get a symbol not found error.

Kapil
  • 817
  • 2
  • 13
  • 25
user2442072
  • 437
  • 2
  • 7
  • 16
  • 3
    You are using a raw `HashMap`, so of course both the key and the value are of type `Object` as far as the compiler is concerned. – Eran Dec 17 '19 at 06:42
  • Just provide generic type information (`Map`) as the return type for your method and wherever you declare the hashmap. – Robby Cornelissen Dec 17 '19 at 06:43

1 Answers1

5

You are not preserving the parameterized type.

Either modify,

HashMap branches = new HashMap<String, String[]>();

to

HashMap<String, String[]> branches = new HashMap<>();

and change function signature to public HashMap<String, String[]> getBranches()

Or do a typecast when you are reading from the HashMap.

System.out.println((String[])(branch[0]))
Adwait Kumar
  • 1,552
  • 10
  • 25