java 如何获取Arraylist的最后三个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5964319/
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
How to get the last three value of Arraylist
提问by RAAAAM
Hi How can i get last three values of list.i tried this
嗨,我如何获得列表的最后三个值。我试过这个
stringAry.get(stringAry.size()-1);
But it displays only last item of list. How can we get last three values of list. pls guide me. Is that possible to store all this three values in String array
但它只显示列表的最后一项。我们如何获得列表的最后三个值。请指导我。是否可以将所有这三个值存储在 String 数组中
回答by mre
List<String> subList = stringAry.
subList(fromIndex, toIndex)
;
List<String> subList = stringAry.
subList(fromIndex, toIndex)
;
回答by Martijn Courteaux
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);
}
回答by Sean Patrick Floyd
To make sthupahsmaht's answer complete:
为了使 sthupahsmaht 的回答完整:
List<String> subList = stringAry.subList(fromIndex, toIndex);
String[] asArray = subList.toArray(subList.size());
回答by amynbe
To get a list containing only the last 3 elements:
要获取仅包含最后 3 个元素的列表:
if ( stringAry.size() > 3 )
{
stringAry = stringAry.subList( stringAry.size() - 3, stringAry.size() );
}
回答by user3506443
Just another possible solution:
只是另一种可能的解决方案:
stringAry.subList(Math.max(0, stringAry.size() - 3), stringAry.size())
Fetches the last three if the size is three or more otherwise returns all available elements.
如果大小为三个或更多,则获取最后三个,否则返回所有可用元素。