java 检查列表中的对象是否是最后一个(按日期)的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3874580/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:47:40  来源:igfitidea点击:

Best method to check if an object in a list is the last (by date)

javalistcollections

提问by Kévin_Bransard

I dont know what is the best way to check if my object in my list is the last created.

我不知道检查列表中的对象是否是上次创建的最佳方法是什么。

What would be the optimal method to do it ?

这样做的最佳方法是什么?

Should I get the last element in the list and check if my given element is the last ?

我应该获取列表中的最后一个元素并检查我的给定元素是否是最后一个?

回答by Jigar Joshi

use this check

使用此检查

listObj.indexOf(yourObject) == (listObj.size() -1);  

Note:The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

注意:List<> 类确实保证了排序 - 除非您明确对列表进行排序,否则内容将按照您添加它们的顺序保留在列表中,包括重复项。

回答by Andy

This depends a lot on your implementation.

这在很大程度上取决于您的实施。

If your objects are appended to the end of the list in order of creation then the first item in the list (index 0) will be the oldest.

如果您的对象按创建顺序附加到列表的末尾,则列表中的第一项(索引 0)将是最旧的。

If the objects in your list are appended in an unknown order and your objects have a method to query the creation date, you could either:

如果列表中的对象以未知顺序附加并且您的对象具有查询创建日期的方法,您可以:

  1. implement a sorted list based on the object creation date
  2. iterate through every item in your list and find the oldest object
  1. 实现基于对象创建日期的排序列表
  2. 遍历列表中的每个项目并找到最旧的对象

Option 1 incurs overhead when items are added to the list or when you explicitly sort the list. Option 2 has overhead when you want to retrieve the oldest object.

将项目添加到列表中或对列表进行显式排序时,选项 1 会产生开销。当您想要检索最旧的对象时,选项 2 会产生开销。

回答by MikeTheReader

If you're looking to order your objects by a specific property (such as it's date property), take a look at the Comparable interface (http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html). If you implement this interface (or a Comparator), the collections provided by the Java API can be used to automatically sort the objects.

如果您希望通过特定属性(例如它的日期属性)对对象进行排序,请查看 Comparable 接口(http://download.oracle.com/javase/6/docs/api/java/lang /Comparable.html)。如果您实现此接口(或 Comparator),则 Java API 提供的集合可用于自动对对象进行排序。