【发布时间】:2012-09-15 03:30:53
【问题描述】:
我想检查字符串值 val 是否包含在字符串列表中,我们将其称为 stringList。
我正在这样做
if(stringList.contains(val)){
System.out.println("The value is in there");
}
else{
System.out.println("There's no such value here");
}
但似乎总是不包括该值。这是因为具有相同字符的两个字符串值实际上并不相等吗?对于“自制”类,我可以实现 hashCode() 和 equals() 并解决这个问题,我可以为 String 数据做什么?
编辑:
这里概述了我获得 val 的方式:
List<String> stringList = new ArrayList<String>();
stringList.add("PDT");
stringList.add("LDT");
stringList.add("ELNE");
String myFile = "/folder/myFile";
InputStream input = new FileInputStream(myFile);
CSVReader reader = new CSVReader(new InputStreamReader(input), ',','"', 1);
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
if (nextLine[6] != null){
String val = nextLine[6];
if(stringList.contains(val)){
System.out.println("Success");
}
}
}
}
【问题讨论】:
-
你从哪里得到这个
val?可能是编码问题 -
除了 Binyamins 的问题:stringList 是什么运行时类型?
-
它取自 .csv 文件,因此您可能是正确的。有什么我可以做的 - 我可以强制两者的编码相同吗?
-
您能否向包含
val的构造/声明/类型的代码片段显示一些上下文? -
是的,我会这样做,我还想说...我使用了 val.equals(aValThatIsInStringList) ...也就是说,我使用了 equals 与单个项目进行比较在 stringList ...我想如果它与编码相关,这将不起作用(但我不确定)
标签: java string list equals contains