代码之家  ›  专栏  ›  技术社区  ›  Ankur

Java包含无法按预期工作,因为“someString”!=“someString”

  •  7
  • Ankur  · 技术社区  · 13 年前

    我想检查字符串值 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");
                }
            }
        }
    }
    
    5 回复  |  直到 13 年前
        1
  •  14
  •   Lukas Eder    13 年前

    ArrayList.contains() 使用 Object.equals() 检查是否相等( hashCode() 未参与 List )。这适用于字符串。也许,你的字符串真的不包含在列表中。。。

    您可能忽略了一些空白、大小写或编码差异。。。

        2
  •  4
  •   Tom Hawtin - tackline    13 年前

    请提供更多代码!

    这样可以:

    import java.util.*;
    
    public class Contains {
        public static void main(String[] args) {
            List<String> stringList = new ArrayList<String>();
            stringList.add("someString");
            String val = new String("someString");
            if (stringList.contains(val)) {
                System.out.println("The value is in there");
            } else {
                System.out.println("There's no such value here");
            }
        }
    }
    
        3
  •  4
  •   Sébastien Le Callonnec    13 年前

    这听起来不对: contains 使用 equals 而不是 == ,因此,如果字符串在列表中,则应该找到它。这可以在 indexOf 超类的方法 AbstractList 由使用 ArrayList

    编辑后,请确保 trim 先字符串后执行 包含 ,否则它们可能包含 newline 个字符。

        4
  •  1
  •   Vitaliy    13 年前

    尝试以下操作,首先通过迭代列表并分别检查每个元素,使检查更加具体。然后,当你击中你期望相等的元素时,这就是你应该看到的。检查它们是否真的相等。也许有案例差异?(或者其他一些难以捉摸但显而易见的差异,比如空白?)

        5
  •  1
  •   TuGordoBello Sebastian Thees    3 年前

    尝试覆盖 equals() ,以便您可以指定需要比较相等的属性…:P