我想检查一个字符串值 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() 并解决这个问题,我可以为字符串数据做些什么?
编辑:
这里概述了我获取 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");
}
}
}
}
最佳答案
ArrayList.contains()
使用Object.equals()
来检查是否相等(hashCode()
不参与列表
)。这适用于字符串。可能,您的字符串确实不包含在列表中...
您可能忽略了一些空格或大写/小写或编码差异...
关于Java 包含不能按预期工作,因为 "someString"!= "someString",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552048/