简体   繁体   English

如何在Java中搜索保存在我的arraylist中的lastName?

[英]how do i search lastNames saved in my arraylist in java?

public void searchLastName(String lastName)
{
    int size = list.size();

    for(int i = 0 ; i < size ; i++)
    {
        if(list.get(i).getLastName().equals(lastName))
            System.out.print(lastName+ " is located at " +i);
        else
            System.out.println("Cant find at loc:" +i);

    }
}

is there any problem with this code?? 这段代码有什么问题吗? i cant search the lastName.. please help me guys 我无法搜索姓氏。.请帮助我

this is from class Person 这是来自班级的人

public String getLastName() { return lastName; }

What's wrong with your code is that it will print out the "Can't find..." message for all locations that do not match, even if some locations do match. 您的代码的问题在于,即使某些位置匹配,它也会为所有不匹配的位置打印出“找不到...”消息。 Perhaps that's what you want. 也许这就是您想要的。 However, if you want one location where lastName is found, you can do something like this: 但是,如果您想找到一个找到lastName位置,则可以执行以下操作:

int found = -1;
for (int i = 0; i < size && found == -1; ++i) {
    if (list.get(i).getLastName().equals(lastName)) {
        found = i;
    }
}
if (found >= 0) {
    System.out.print(lastName+ " is located at " + found);
} else {
    System.out.println("Cant find " + lastName);
}

If you want all locations where it is found, you can do this: 如果要在所有位置找到它,可以执行以下操作:

List<Integer> found = new ArrayList<Integer>();
for (int i = 0; i < size; ++i) {
    if (list.get(i).getLastName().equals(lastName)) {
        found.add(i);
    }
}
if (found.isEmpty()) {
    System.out.println("Cant find " + lastName);
} else {
    System.out.print(lastName+ " is located at " + found.toString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM