Queue
은 Collection
입니다. 따라서 해당 요소를 항상 Collection
에 복사하면 주문을 검색 할 수 있습니다.
List<YourType> copy = new ArrayList<YourType>(yourQueue);
if(copy.indexOf(obj1)<copy.indexOf(obj2)){
// some code here
}
물론 이것은 매우 비효율적이지만 작동합니다. 그래서, 물론
/**
* Returns -1 if a occurs in the collection before b, 1 if b occurs before a
* and 0 otherwise.
*/
public static <T> int comparePositionInCollection(final T a,
final T b,
final Collection<T> collection){
// todo: check for a==null, b==null, a.equals(b)
final Iterator<T> iterator = collection.iterator();
boolean foundA = false;
boolean foundB = false;
int result = 0;
while(iterator.hasNext()){
final T t = iterator.next();
if(a.equals(t)){
if(foundB){
result = 1;
break;
}
foundA = true;
} else if(b.equals(t)){
if(foundA){
result = -1;
break;
}
foundB = true;
}
}
return result;
}
당신이 반복자를 액세스하기 전에 큐를 동기화 할 것이다 : A는 iterator()
을 통해 그것을 할 것
또 다른 방법은 (이 일을하는 동안 당신은 아마 큐를 동기화해야합니다) 이것은 또한 비효율적이다.
큐가 아닌 다른 데이터 구조를 사용할 수 있습니까? – Bernard
효율성 때문에 대기열을 사용하고 싶습니다. http://stackoverflow.com/questions/4724995/lock-free-concurrent-linked-list-in-java – ptikobj
을 참조하십시오. 아마도이 경우 사용하는 것이 더 좋습니다. List list = Collections.synchronizedList (new LinkedList