【发布时间】:2012-08-08 09:50:02
【问题描述】:
我遇到了一个非常不寻常的问题。
基本上,我试图从字符串映射到字符串中获取与键关联的值。
我知道我正在使用的密钥存在;我使用的是我用来放入它的相同字符串!
我的代码中都打印了语句,这就是我遇到的情况...
这是我的字典characterDictionary
{thusChar=∴, spaceChar= , plusChar=+, equalsIndent=#, multiplyChar=×, equalsChar==, newlineChar=\n, divideChar=÷, subjectChar=:, variableIndent=@}
最后一个键“variableIndent”很麻烦!
这是代码...
System.out.println ( characterDictionary.get("variableIndent") );
不恰当地输出:null
我已经检查、双重检查和三次检查我的代码。
"variableIndent" 键和 characterDictionary.get("variableIndent") 的字符串参数之间绝对没有区别,但它的行为就像这个键不存在一样。
我可以绝对保证这个键是存在的,并且两个字符串是相同的。
字典的所有其他元素(我检查过的元素;到目前为止大约 3 个)都正常检索。为什么带有“@”值的“variableIndent”会出现?
您可能会注意到字典包含非 ASCII 字符,例如“thusChar”。这有关系吗?
谢谢
(这似乎是一个非常简单和微不足道的问题,好像我犯了一个可怜的愚蠢的错误,但我就是无法解决它!)
编辑:
好的,这必须与编码有关。
我从字典中取出字符串键并将其与我的 get 参数进行比较。
打印时,它们是相同的,但 java 说它们不相等。
密钥字符串来自 UTF-8 编码的文本文件,而参数字符串来自 java Eclipse 文字。
但是字符是相同的。
是什么问题,我该如何解决?
谢谢!
编辑:
嗯,这就是幕后实际发生的事情。
我有一个 UTF-8 文本文件,其中包含以下内容...
variableIndent,@
equalsIndent,#
spaceChar,
newlineChar,\n
multiplyChar,×
divideChar,÷
plusChar,+
equalsChar,=
subjectChar,:
thusChar,∴
我通过将文件的每一行作为ArrayList<String> 元素读取,通过传递文件的目录来“加载”该文件:
private static ArrayList<String> readLinesFile(String ResourceFile) {
ArrayList<String> Lines = new ArrayList<String>();
try{
InputStream fstream = FileManager.class.getResourceAsStream(ResourceFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
Lines.add(strLine); }
in.close(); }
catch (Exception e) {
System.out.println("Error: " + e.getMessage()); }
return Lines; }
到这里为止一切都很好。
然后我将这个 ArrayList 传递给一个函数,该函数通过“,”字符分割每个元素(使用个人包中的函数;这绝对不是问题),并将第一部分作为键添加到新的第二部分字典。
private static Map<String, String> generateBaseUnits_Characters_Prefixes(ArrayList<String> FileContent) {
Map<String, String> BaseUnitsCache = new HashMap<String, String>();
ArrayList<String> currentLine;
for (int i=0; i<FileContent.size(); i++) {
currentLine = MiscellaneousFunctions.splitString(FileContent.get(i), ",");
BaseUnitsCache.put(currentLine.get(0), currentLine.get(1)); }
return BaseUnitsCache; }
这会产生导致所有麻烦的字典。
我有一组与文本文件中的字符名称相对应的 Key Literals,用于访问程序中的字典。
public static String variableIndentKey = "variableIndent";
public static String equalsIndentKey = "equalsIndent";
public static String spaceCharKey = "spaceChar";
public static String newlineCharKey = "newlineChar";
public static String multiplyCharKey = "multiplyChar";
public static String divideCharKey = "divideChar";
public static String plusCharKey = "plusChar";
public static String equalsCharKey = "equalsChar";
public static String subjectCharKey = "subjectChar";
public static String thusCharKey = "thusChar";
问题来了:
文本文件的第一行在字典中'screw up'。
它被添加到字典中,并在 keySet 和字典的打印格式中正确显示,但尝试访问它会返回“null”。
(在这种情况下,它是 variableIndent。如果我将 variableIndent 放在文本文件中的其他位置,equalsIndent 搞砸了,等等)
发生了什么事!?
我有一个狡猾的功能吗?!
他们在其他所有方面都运作良好。
谢谢!
【问题讨论】:
-
为了保证这个键存在,遍历这个映射中的所有键并打印它们的值。
-
你能展示一些重现行为的东西吗?
-
编辑了 OP。相信这是文本文件和 Eclipse 之间的编码问题。
标签: java string dictionary map null