gpt4 book ai didi

java - 如何使Set中的元素始终是第一个元素

转载 作者:行者123 更新时间:2023-12-02 05:58:49 25 4
gpt4 key购买 nike

我有一个树集,里面有很多元素。我把它们按字母顺序排列。我真的可以让它的元素始终是第一个元素而不干扰排序顺序吗?

例如:我希望“partnumber”元素始终是集合中的第一个元素。能做到吗?预先感谢!

最佳答案

这应该允许您将头元素添加到任何Set

public class HeadSet<T> extends AbstractSet<T> implements Set<T> {
// The extra item to add at the head.
final T head;
// The rest of the items.
final Set<T> body;

public HeadSet(T head, Set<T> body) {
this.head = head;
this.body = body;
}

@Override
public Iterator<T> iterator() {
// Iterator starts with the head element and then delegates to the body iterator.
return new Iterator<T>() {
private T next = head;
private Iterator<T> i = body.iterator();

@Override
public boolean hasNext() {
if (next == null && i.hasNext()) {
next = i.next();
}
return next != null;
}

@Override
public T next() {
if (hasNext()) {
T n = next;
next = null;
return n;
} else {
throw new NoSuchElementException();
}
}

};
}

@Override
public int size() {
// Size is one more than the size of the body.
return 1 + body.size();
}
}

public void test() {
Set<String> bodySet = new TreeSet<>(Arrays.asList("One", "Two"));
Set<String> mySet = new HeadSet("Choose part number ...", bodySet);
System.out.println(mySet);
}

关于java - 如何使Set中的元素始终是第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847052/

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