简体   繁体   English

删除列表的一部分并成功返回true的方法的正确语法是什么?

[英]What is the correct syntax of a method that deletes part of a list and returns true if succesful?

I m trying to create a method that searches the content of a list called authors looking for the element (the author's name) given as arg, and then deletes the specific field. 我正在尝试创建一种方法,该方法搜索名为authorslist的内容,以查找以arg给出的元素(作者的名字),然后删除特定字段。 If successful it returns true. 如果成功,则返回true。 But it won't work for some reason. 但是由于某种原因,它将无法正常工作。 I believe the error lies in the authors.remove(authorName); 我相信错误在于authors.remove(authorName); because the main class will not erase anything when given the order Book.removeAuthorByName("White"); 因为按给定Book.removeAuthorByName("White");的顺序, main类不会删除任何内容Book.removeAuthorByName("White"); .

public boolean removeAuthorByName(String authorName){
    boolean val = authors.contains(authorName);
    for (int i = 0; i <= numAuthors; i++){
        if(val = true){
            authors.remove(authorName);
            authors.trimToSize();
        }
    }
    return val;
}

public int listSize(){
    return authors.size();
}

Little more concise and better will be 更加简洁和更好

public boolean removeAuthorByName(String authorName){

     int index = authors.indexOf(authorName);
     if(index > -1){
         authors.remove(index);
         return true;
     }
     return false;
 }

First of all, you should check whether your list supports the remove(Object) method; 首先,您应该检查列表是否支持remove(Object)方法。 it does because otherwise you would have received an UnsupportedOperationException. 这样做是因为否则您将收到UnsupportedOperationException。

You can simply have to call authors.remove(name); 您只需要调用authors.remove(name);。 the method will return true if the passed name was found and deleted successfully - see the documentation . 如果找到并成功删除了传递的名称,则该方法将返回true-请参阅文档

Remove the while loop check using if clause. 使用if子句删除while循环检查。 Also check case sensitivity 还要检查是否区分大小写

if(list.contains(authorname)){

    list.remove(authorname);

    return true;
 }
 else
 {
    return false;
 }

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

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