Java包含的内容无法正常运行,因为"someString" !="someString"; [英] Java contains doesn't work as expected because "someString" != "someString"

查看:103
本文介绍了Java包含的内容无法正常运行,因为"someString" !="someString";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查字符串列表中是否包含字符串值val,我们将其称为stringList.

I want check whether a String value val is contained within a List of Strings lets call it stringList.

我正在这样做

if(stringList.contains(val)){
  System.out.println("The value is in there");
}
else{
  System.out.println("There's no such value here");
}

但是似乎总是不包含该值.这是因为两个具有相同字符的String值实际上不相等吗?对于自制"类,我可以实现hashCode()和equals()并解决此问题,该如何处理String数据?

But it always seems to be that the value is not included. Is this because two String values that have the same characters are not actually equal? For a "home-made" class I could implement hashCode() and equals() and fix this, what can I do for String data?

这里概述了我获得val的方式:

The way I am getting val is outlined here:

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()不涉及hashCode()).这适用于字符串.可能您的字符串确实未包含在列表中...

ArrayList.contains() uses Object.equals() to check for equality (hashCode() is not involved in List). This works well for strings. Probably, your string really isn't contained in the list...

您可能已经忽略了一些空格,大小写或编码差异...

You've probably overlooked some whitespace or upper/lower-case or encoding difference...

这篇关于Java包含的内容无法正常运行,因为"someString" !="someString";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆