Java - 从 ArrayList 中删除最后一个已知项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3515496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:26:36  来源:igfitidea点击:

Java - remove last known item from ArrayList

javaarraylist

提问by test

OK, so here is my ArrayList:

好的,这是我的ArrayList

private List<ClientThread> clients = new ArrayList<ClientThread>();

and here is what I am trying to do:
I am trying to remove the last known item from the ArrayListI posted above. I'm trying to do this with the code below:

这就是我想要做的:
我试图从ArrayList我上面发布的中删除最后一个已知项目。我正在尝试使用以下代码执行此操作:

    } catch(SocketException re) {


                            String hey = clients.get(clients.size());
                            ClientThread.remove(hey);
                            System.out.println(hey + " has logged out.");
                            System.out.println("CONNECTED PLAYERS: " + clients.size());
}

but I am getting this error:

但我收到此错误:

C:\wamp\www\mystikrpg\Server.java:147: incompatible types
found   : Server.ClientThread
required: java.lang.String
                        String hey = clients.get(clients.size());
                                                ^
C:\wamp\www\mystikrpg\Server.java:148: cannot find symbol
symbol  : method remove(java.lang.String)
location: class Server.ClientThread
                        ClientThread.remove(hey);
                                    ^
2 errors

What am I doing wrong? It's supposed to remove the last known item from my ArrayList.

我究竟做错了什么?它应该从我的ArrayList.

采纳答案by jonescb

It should be:

它应该是:

ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);

Or you can do

或者你可以做

clients.remove(clients.size() - 1);

The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.

减号是因为 size() 返回元素的数量,但 ArrayList 的第一个元素的索引是 0 而不是 1。

回答by j flemm

First error: You're casting a ClientThreadas a Stringfor some reason.

第一个错误:您出于某种原因将 a 转换ClientThread为 a String

Second error: You're not calling removeon your List.

第二个错误:你没有调用remove你的List.

Is is homework? If so, you might want to use the tag.

是家庭作业吗?如果是这样,您可能想要使用该标签。

回答by Andre Holzner

The compiler complains that you are trying something of a list of ClientThreadobjects to a String. Either change the type of heyto ClientThreador clientsto List<String>.

编译器抱怨您正在尝试将ClientThread对象列表添加到String. 更改heytoClientThreadclientsto的类型List<String>

In addition: Valid indices for lists are from 0 to size()-1.

另外:列表的有效索引是从 0 到 size()-1。

So you probably want to write

所以你可能想写

   String hey = clients.get(clients.size()-1);

回答by Tim Stone

You're trying to assign the return value of clients.get(clients.size())to the string hey, but the object returned is a ClientThread, not a string. As Andre mentioned, you need to use the proper index as well.

您试图将 的返回值分配给clients.get(clients.size())string hey,但返回的对象是 a ClientThread,而不是字符串。正如安德烈所说,您还需要使用正确的索引。

As far as your second error is concerned, there is no static method remove()on the type ClientThread. Really, you likely wanted the remove method of your Listinstance, clients.

就您的第二个错误而言,remove()type没有静态方法ClientThread。确实,您可能想要List实例的 remove 方法,clients.

You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:

您可以从列表中删除最后一项(如果有),如下所示。由于 remove 还返回被删除的对象,您可以捕获返回并使用它打印出名称:

int size = clients.size();

if (size > 0) {
    ClientThread client = clients.remove(size - 1);

    System.out.println(client + " has logged out.");
    System.out.println("CONNECTED PLAYERS: " + clients.size());
}

回答by Peter Tillemans

clients.getwill return a ClientThreadand not a String, and it will bomb with an IndexOutOfBoundsExceptionif it would compile as Java is zero based for indexing.

clients.get将返回 aClientThread而不是 a StringIndexOutOfBoundsException如果它会编译为 Java 基于零的索引,它将用 an 进行轰炸。

Similarly I think you should call removeon the clientslist.

同样,我认为你应该removeclients名单上打电话。

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedListin this case though.

LinkedList在这种情况下,我会使用 a 的堆栈函数。

ClientThread hey = clients.removeLast()

回答by Kerem Baydo?an

This line means you instantiated a "List of ClientThread Objects".

此行表示您实例化了“ClientThread 对象列表”。

private List<ClientThread> clients = new ArrayList<ClientThread>();

This line has two problems.

这条线有两个问题。

String hey = clients.get(clients.size());

1.This part of the line:

1.这部分线路:

clients.get(clients.size());

ALWAYSthrows IndexOutOfBoundsExceptionbecause a collections size is always one bigger than its last elements index;

总是抛出IndexOutOfBoundsException因为集合大小总是比它的最后一个元素索引大 1;

2.Compiler complains about incompatible types because you cant assign a ClientThread object to String object. Correct one should be like this.

2.编译器抱怨类型不兼容,因为您不能将 ClientThread 对象分配给 String 对象。正确的应该是这样的。

ClientThread hey = clients.get(clients.size()-1);

Last but not least. If you know index of the object to remove just write

最后但并非最不重要的。如果您知道要删除的对象的索引,则只需写入

 clients.remove(23); //Lets say it is in 23. index

Don't write

不要写

   ClientThread hey = clients.get(23); 

   clients.remove(hey);

because you are forcing the list to search for the index that you already know. If you plan to do something with the removed object later. Write

因为您正在强制列表搜索您已经知道的索引。如果您打算稍后对已删除的对象执行某些操作。写

   ClientThread hey = clients.remove(23); 

This way you can remove the object and get a reference to it at the same line.

通过这种方式,您可以删除对象并在同一行获得对它的引用。

Bonus: Never ever call your instance variable with name "hey". Find something meaningful.

奖励:永远不要使用名称“嘿”调用您的实例变量。找点有意义的。

And Here is your corrected and ready-to-run code:

这是您更正且可以运行的代码:

public class ListExampleForDan {

    private List<ClientThread> clients = new ArrayList<ClientThread>();

    public static void main(String args[]) {

        clients.add(new ClientThread("First and Last Client Thread"));

        boolean success = removeLastElement(clients);

        if (success) {

            System.out.println("Last Element Removed.");

        } else {

            System.out.println("List Is Null/Empty, Operation Failed.");

        }

    }

    public static boolean removeLastElement(List clients) {

        if (clients == null || clients.isEmpty()) {

            return false;

        } else {

            clients.remove(clients.size() - 1);

            return true;

        }

    }
}

Enjoy!

享受!

回答by fastcodejava

You need to understand java generics. You have a list of ClientThreadbut trying to get String. You have other errors, but this one is very basic.

您需要了解java 泛型。您有一个列表,ClientThread但试图获取String. 您还有其他错误,但这是非常基本的错误。