字符串[]作为值的HashMap:需要数组,但java.lang.Object
我正在调用一个单独的类方法,该方法将返回一个以字符串数组作为值的hashmap。从方法内部,可以将值作为数组访问,但当返回到调用类方法时,它“成为”一个对象并生成错误: 需要数组,但找到java.lang.Object 调用方法:字符串[]作为值的HashMap:需要数组,但java.lang.Object,java,Java,我正在调用一个单独的类方法,该方法将返回一个以字符串数组作为值的hashmap。从方法内部,可以将值作为数组访问,但当返回到调用类方法时,它“成为”一个对象并生成错误: 需要数组,但找到java.lang.Object 调用方法: public HashMap getBranches(){ HashMap branches = dbMgr.getBranches(); branches.forEach( (index, branch) -> { System.o
public HashMap getBranches(){
HashMap branches = dbMgr.getBranches();
branches.forEach( (index, branch) -> {
System.out.println(branch[0]); // This generates the error.
});
return(branches);
}
返回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;
HashMap branchs=newhashmap();
公共HashMap getBranchs(){
System.out.println(“\n[>]正在获取分支…\n”);
DataFormatter formatter=新的DataFormatter();
Sheet Sheet=tables.get(“tbl_library_branch”).getSheetAt(0);
迭代器rowIter=sheet.rowitter();
while(rowIter.hasNext()){
Row=(Row)rowIter.next();
迭代器cellIter=row.cellIterator();
while(cellIter.hasNext()){
String primaryKey=formatter.formatCellValue((Cell)cellIter.next());
String name=formatter.formatCellValue((Cell)cellIter.next());
字符串地址=formatter.formatCellValue((Cell)cellIter.next());
字符串[]分支=新字符串[2];
分支[0]=名称;
分支机构[1]=地址;
分支。put(主键,分支);
}
}
返回分支;
我也尝试过使用ArrayList,但随后出现了一个symbol not found错误。您没有保留参数化类型 要么修改
HashMap branches = new HashMap<String, String[]>();
您使用的是原始的
HashMap
,因此就编译器而言,键和值的类型当然都是Object
。只需提供泛型类型信息(Map
)作为方法的返回类型以及声明HashMap的任何位置。
HashMap<String, String[]> branches = new HashMap<>();
System.out.println((String[])(branch[0]))