获取arraylist中的最后一个元素

use*_*009 6 java random arraylist

在下面的代码中,它只调用一次元素.我怎样才能打印出"这是arraylist中的最后一个元素",当一切都被删除后,只剩下一个元素.

ArrayList<String> Responselist = new ArrayList<String>();
Responselist.add(CommentResponse());
Responselist.add(TriviaResponse());
Responselist.add(CriticResponse());
String[] SelectRand = new String [3];

for (int i = 0; i < SelectRand.length; ++i)
{
    int rnd = (int) (Math.random() * Responselist.size());
    SelectRand[i] = Responselist.get(rnd);
    Responselist.remove(rnd);
}

for (String x : SelectRand)
{
    if (!(Responselist.isEmpty()))
    {
        System.out.println(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

kle*_*e85 6

你可以控制arraylist的大小,id est

if (arraylist.size()==1){
    System.out.println("this is the last element in the arraylist");
}
Run Code Online (Sandbox Code Playgroud)

如果你想打印最后一个元素你可以访问它(索引= 0,如果它只是一个元素)

arraylist.get(arraylist.size()-1);
Run Code Online (Sandbox Code Playgroud)


Bla*_*ght 1

我想这应该可以做到:

if (list.size() == 1) {
  System.out.println(list.get(list.size() - 1)) // or just .get(0) of course...
} else {
  System.out.println("List is empty or bigger than one")
}
Run Code Online (Sandbox Code Playgroud)