当前位置:   article > 正文

Java列表中寻找最后一个元素的方法

java list 最后一个元素

Java实现寻找列表List中最后一个元素

如何在一个元素列表List中找到最后一个元素?

import java.util.LinkedList;

import java.util.List;

import java.util.NoSuchElementException;

/**

* (*) Find the last element of a list.

*

* Check P01Test class for test cases related to this problem.

*/

public class P01 {

/*

You could solve this using many different approaches.

If you work with List interface then you can find the last element using List size as shown below.

*/

public static T last(List elements) {

int numberOfElements = elements.size();

return elements.get(numberOfElements - 1);

}

/*

Another way to solve this is by using LinkedList instead of a List.

LinkedList provides a builtin getLast method.

*/

public static T last(LinkedList elements) {

return elements.getLast();

}

/*

A functional approach could be to use recursion.  We call the function recusively with a sub list which ignores the 0th element.

When we reach the end i.e. size of the list is 1 then we return that element.

*/

public static T lastRecursive(List elements) {

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

throw new NoSuchElementException();

}

if (elements.size() == 1) {

return elements.get(0);

}

return lastRecursive(elements.subList(1, elements.size()));

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/77384
推荐阅读
相关标签
  

闽ICP备14008679号