gpt4 book ai didi

java - 检索插入顺序中的 LinkedHashSet 元素并将它们保存到局部变量中

转载 作者:行者123 更新时间:2023-11-30 08:02:59 24 4
gpt4 key购买 nike

我有一个 linkedhashset,我需要从中获取与插入元素相同的元素。要检索,我无法按准确的插入顺序获取元素。

将 linkedHashset 转换为 List 以通过索引获取,但担心转换为 list 会打乱我的元素并改变顺序

  LinkedHashSet<String> personDetails = new LinkedHashSet<String>();
//persondetails => John, kennedy, Female
List<String> details = new ArrayList<>(personDetails);
String firstName = details.get(0);
String lastName = details.get(1);
String gender = details.get(2);

转换为列表偏离了我的主要目标,即首先按插入顺序检索它们,因为列表不保留顺序。

你能给我建议一个替代方案还是我的错误吗?

最佳答案

首先,您无需将 LinkedHashSet 转换为 List 即可根据插入顺序检索它们。您可以使用迭代器迭代 Set。

例如:

Iterator<String> iter = personDetails.iterator();
String firstName = null;
if (iter.hasNext())
firstName = iter.next();
String lastName = null;
if (iter.hasNext())
lastName = iter.next();
String gender = null;
if (iter.hasNext())
gender = iter.next();

其次,当您使用接受源 Collcetion 作为输入的构造函数创建 ArrayList 时,Collection 会按顺序迭代将元素添加到 ArrayList。迭代顺序取决于Collection 的迭代器的实现,在LinkedHashSet 的情况下,迭代顺序是插入的顺序。因此,您的 List 将保留插入顺序。

您可以在 Javadoc 中看到这一点:

java.util.ArrayList.ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

关于java - 检索插入顺序中的 LinkedHashSet 元素并将它们保存到局部变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com