我正在调用一个单独的类方法,该方法将返回一个带有字符串数组作为值的哈希图。从方法内部,这些值可以作为数组访问,但是当返回到调用类方法时,它“变成”一个对象并生成错误:
需要数组,但找到了 java.lang.Object
调用方法:
public HashMap getBranches(){
HashMap branches = dbMgr.getBranches();
branches.forEach( (index, branch) -> {
System.out.println(branch[0]); // This generates the error.
});
return(branches);
}
Run Code Online (Sandbox Code Playgroud)
返回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;
Run Code Online (Sandbox Code Playgroud)
我也试过使用 ArrayLists,但后来我得到一个符号未找到错误。
您没有保留参数化类型。
要么修改,
HashMap branches = new HashMap<String, String[]>();
Run Code Online (Sandbox Code Playgroud)
到
HashMap<String, String[]> branches = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
并将函数签名更改为 public HashMap<String, String[]> getBranches()
或者在读取 HashMap 时进行类型转换。
System.out.println((String[])(branch[0]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |