我想維護一個名爲'ClientStatus'的對象列表,其中除了客戶端標識(id)和一些時間字段(即與此客戶端相關的內容)外,不包含任何內容。此列表應按照此時間字段按升序排序。我想支持的操作是:如何維護訂購鏈接列表並添加,刪除java中的元素
* peek and remove an entry from the beginning
* Search the list for an entry and if found, remove it
* Add an entry to this list
我期待每一個新條目有時間> =在列表中的最後一項,但有競爭狀態,我可能會失去訂單價值的可能性。所以我認爲從頭到尾遍歷清單將是最省時的解決方案。
這些都是我用DS:
的LinkedList的ListIterator和作爲的ListIterator允許您遍歷從最終的元素,並添加新條目,而迭代。但代碼看起來凌亂:
說我的列表中有值:2 3 6 7 9,我要加5
ListIterator<Integer> it = list.listIterator(list.size()); while (it.hasPrevious()) { if (it.previous().intValue() <= 5) { it.next(); break; } }
有沒有更好的方式來做到這一點?
我也試過使用LinkedList和Dequeue,但降序迭代器不讓你添加/刪除條目。我試圖計數指數,但隨後設置(指數,價值)取代了現有的條目。如何在列表中插入條目?
======================修訂版2 =================== =========
根據一致意見,我決定使用SortedSet,如果我所編寫的代碼可以在Comparator和equals之間的一致性方面進行審查,我將不勝感激。
private static class ClientStatus {
public long id;
public long time;
public ClientStatus(final long id, final long time) {
this.id = id;
this.time = time;
}
@Override
public boolean equals(final Object o) {
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
if (this == o) {
return true;
}
ClientStatus obj = (ClientStatus) o;
return this.id == obj.id;
}
}
public static void main(String[] args) {
SortedSet<ClientStatus> active_client_set = new TreeSet<ClientStatus>(
new Comparator<ClientStatus>() {
@Override
public int compare(final ClientStatus o1, final ClientStatus o2) {
if (o1.getClass() != o2.getClass()) {
return -1;
}
if (o1 == o2 || o1.id == o2.id) {
return 0;
}
return (o1.time - o2.time) < 0 ? -1 : +1;
}
}
);
}
我比較ID只有一個客戶端ID不能在列表中的多個條目,而是兩個不同的客戶端可以具有相同的時間值。此代碼似乎不起作用,添加工作正常,但如果我無法刪除基於clientid的條目只。
您是否需要允許重複條目? –
我認爲'SortedSet'可能是要走的路。但是如果你想使用'LinkedList',你似乎通過對索引進行計數來處於正確的軌道上,但是使用'add'方法將會在列表中插入一個新條目。請參閱['LinkedList' javadoc](http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html)。 – ajb