Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last element in arraylist

In the below code, it calls an element exactly once. How can i make it print out "this is the last element in the arraylist" when everything has been removed, and there is only one element remaining.

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);
    }
}
like image 502
user872009 Avatar asked Aug 09 '12 08:08

user872009


1 Answers

You can make a control on the size of the arraylist, id est

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

and if you want to print the last element you can access it as (index=0 in case it is just one element)

arraylist.get(arraylist.size()-1);
like image 96
klebe85 Avatar answered Oct 06 '22 13:10

klebe85