我尝试在类中使用HAshmap,以便从其他类中查找给定产品代码的产品说明。 所有的东西(填充)一切似乎工作正常,但当我尝试使用吸气剂(getdesc)时,我得到一个错误。
我使用的csv文件只有2个filds(cod,des)。后来,我计划从JDBC SQL服务器源填充hashmap。
我可能会使用错误的语法。如果有人可以提供帮助,我会感到沮丧。
这是我目前的班级代码:
package bookRecommender;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class ProdutoDescricao
{
public static void main(String[] args) {}
@SuppressWarnings({ "resource", "unused" })
public static void populate(String[] args) throws IOException {
Map<String, ArrayList<String>> produtos=null;
try {
String csvFile = "Data/produto_descricao.csv";
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
StringTokenizer st = null;
produtos= new HashMap<String, ArrayList<String>>();
int lineNumber = 0;
int tokenNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
tokenNumber++;
String token_lhs=st.nextToken();
String token_rhs= st.nextToken();
ArrayList<String> arrVal = produtos.get(token_lhs);
if (arrVal == null) {
arrVal = new ArrayList<String>();
produtos.put(token_lhs,arrVal);
}
arrVal.add(token_rhs);
}
}
System.out.println("Final Hashmap is : "+produtos);
} catch (Exception e) {
System.err.println("CSV file cannot be read : " + e);
}
}
public String getdesc (long cod)
{
return produto.get(cod);
//Here is the sysntax error
}
}
答案 0 :(得分:0)
produtos= new HashMap<String, ArrayList<String>>()
produtos
它没有值为空白。
ArrayList<String> arrVal = produtos.get(token_lhs);
此行存在问题,您必须先在地图中添加值,然后获取这些值。
答案 1 :(得分:0)
您有一个包含String键和ArrayList值类型的映射,但您尝试使用长键和字符串值类型检索值。
public ArrayList<String> getdesc (String cod)
{
return produtos.get(cod);
}
同时声明字段'produtos':
private static Map<String, ArrayList<String>> produtos;
完整的课程代码:http://pastebin.com/QLZryqT8