How to get the last three values ​​of Arraylist

Hi How can I get the last three values ​​of list.i, tried this

stringAry.get(stringAry.size()-1);

But it only displays the last item in the list. How can we get the last three values ​​of a list. Pls guide me. Is it possible to store all these three values ​​in a String array

+4
source share
5 answers
if (stringAry.size() >= 3) // Make sure you really have 3 elements
{
    List<String> array = new ArrayList<String>();
    array.add(stringAry.get(stringAry.size()-1)); // The last
    array.add(stringAry.get(stringAry.size()-2)); // The one before the last
    array.add(stringAry.get(stringAry.size()-3)); // The one before the one before the last

    System.out.println(array);
}
+11
source

List<String> subList = stringAry. subList(fromIndex, toIndex) ;

+19
source

:

List<String> subList = stringAry.subList(fromIndex, toIndex);
String[] asArray = subList.toArray(subList.size());
+4

, 3 :

if ( stringAry.size() > 3 )
{
    stringAry = stringAry.subList( stringAry.size() - 3, stringAry.size() );
}
0

:

stringAry.subList(Math.max(0, stringAry.size() - 3), stringAry.size())

, , .

0

All Articles