java如何取出list的最后一个值_如何获取ArrayList的最后一个值

我使用micro-util类获取列表的最后一个(和第一个)元素:

public final class Lists {

private Lists() {

}

public static T getFirst(List list) {

return list != null && !list.isEmpty() ? list.get(0) : null;

}

public static T getLast(List list) {

return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null;

}

}

稍微灵活一些:

import java.util.List;

/**

* Convenience class that provides a clearer API for obtaining list elements.

*/

public final class Lists {

private Lists() {

}

/**

* Returns the first item in the given list, or null if not found.

*

* @param The generic list type.

* @param list The list that may have a first item.

*

* @return null if the list is null or there is no first item.

*/

public static T getFirst( final List list ) {

return getFirst( list, null );

}

/**

* Returns the last item in the given list, or null if not found.

*

* @param The generic list type.

* @param list The list that may have a last item.

*

* @return null if the list is null or there is no last item.

*/

public static T getLast( final List list ) {

return getLast( list, null );

}

/**

* Returns the first item in the given list, or t if not found.

*

* @param The generic list type.

* @param list The list that may have a first item.

* @param t The default return value.

*

* @return null if the list is null or there is no first item.

*/

public static T getFirst( final List list, final T t ) {

return isEmpty( list ) ? t : list.get( 0 );

}

/**

* Returns the last item in the given list, or t if not found.

*

* @param The generic list type.

* @param list The list that may have a last item.

* @param t The default return value.

*

* @return null if the list is null or there is no last item.

*/

public static T getLast( final List list, final T t ) {

return isEmpty( list ) ? t : list.get( list.size() - 1 );

}

/**

* Returns true if the given list is null or empty.

*

* @param The generic list type.

* @param list The list that has a last item.

*

* @return true The list is empty.

*/

public static boolean isEmpty( final List list ) {

return list == null || list.isEmpty();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值