我有一个名为 myArraylist
的数组列表,其中包含名为 TStas
的类的项目。 Tstas 有一个名为 st_name 的字符串变量。我想搜索数组列表,查找 st_name 等于要查找的字符串的 TStas
实例,找到后返回 的位置(找到的位置) >TStas
在数组列表中。
public static List<Integer> findplace_byname(String lookfor){
List<Integer> foundplaces = new ArrayList<>(); //list to place posistions of found items
for(int k=0; k<myArraylist.size(); k++) {
TStas a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#"+a.st_name+"#"+lookfor+ "#"); //just to check if everything is read,
if ((a.st_name).equals(lookfor)){
foundplaces .add(k);
}
}
return foundplaces;
}
我的问题是,与 myArraylist
中第一项的 a.st_name 进行比较时,代码无法检测到相等性。
例如:
if I have in myarrailist an item with a.st_name=S9, an item with a.st_name=K9 and another with a.st_name=G4. When lookfor is K9 or G4 all is ok. When searching for the first item in the array having a.st_name=S9 the code fails to "see" the equality. I am using the showMessageDialog to check that the variable is realy read and it is so. Also I tried to delete or change the 1st item in the arraylist, but the same problem goes on: The 1rst item is not found.
这里发生了什么?
编辑 我使用trim() 删除了任何可能的空格,但没有任何改变。然后我在“修剪”字符串上使用 .length() 来获取要比较的每个字符串的长度,我发现由于某种原因,第一个元素在没有任何空格的“S9”时长度为 3!难不成还隐藏着什么王者风范? (我不知道,段落字符还是什么?)
最佳答案
您当前的代码没有问题,请自行检查此代码。
List<Integer> foundplaces = new ArrayList<>();
List<String> myArraylist=new ArrayList<>();
myArraylist.add("S9");
myArraylist.add("K9");
myArraylist.add("G4");
for(int k=0; k<myArraylist.size(); k++) {
String a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#" + a + "#" + "S9" + "#");
if ((a).equals("S9")){
foundplaces .add(k);
System.out.println(k);
}
}
您可以看到它运行良好。与您当前的代码相同。
关于Java:比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20852144/