我的优先级队列存在问题,无法正确排序对象值。
我的代码获取一个字符串,并获取唯一字符的数量,同时还计算每个唯一字符的频率。然后将其放入“字符”和“整数”类型的映射中,并分别分配“键”和“值”。
然后,它获取地图的每个条目,并将其放入字符类型为Integer的PQNode对象中,然后将其提供给Priority Queue。
优先级队列是通过PQNode.java中的compareTo方法按从最低到最高的频率(值)对PQNode进行排序
我尝试在网上搜索并尝试将其排序以进行排序,但没有运气。
public class Counting {
public Counting(String text) {
text = "mississippi river";
Queue<PQNode> fringe = new PriorityQueue<>();
char[] letters = text.toCharArray();
Map<Character, Integer> frequency = new HashMap<>();
for(char letter : letters) {
if(frequency.containsKey(letter)) {
frequency.put(letter, frequency.get(letter) + 1);
}
else {frequency.put(letter, 1);}
}
for(Map.Entry<Character, Integer> element : frequency.entrySet()) {
PQNode pqN = new PQNode(element.getKey(), element.getValue());
fringe.offer(pqN);
}
System.out.println(fringe);
}
}
public class PQNode implements Comparable<PQNode>{
Character c;
int freq;
public PQNode(Character c, int freq) {
this.c = c;
this.freq = freq;
}
public String toString() {
return "[c=" + c + ", freq=" + freq + "]";
}
public int compareTo(PQNode otherFreq) {
return Integer.compare(this.freq, otherFreq.freq);
}
}
预期输出为: [[c =,freq = 1],[c = e,freq = 1],[c = v,freq = 1],[c = m,freq = 1],[c = p,freq = 2], [c = r,freq = 2], [c = s,freq = 4],[c = i,freq = 5]]
但是实际输出是: [[c =,freq = 1],[c = e,freq = 1],[c = v,freq = 1],[c = m,freq = 1],[c = p,freq = 2], [c = r,freq = 2], [c = i,freq = 5],[c = s,freq = 4]]
在频率等于1的情况下,顺序并不重要,但是最后两个元素的顺序错误。有什么想法吗?
答案 0 :(得分:2)
PriorityQueue
不保证会被排序。 PriorityQueue
保证从poll
和peek
收到的下一个项目最少。如果要按顺序订购商品,则必须poll
一件一件地PriorityQueue
,而不要照原样打印TreeSet
。
如果您正在寻找一种将要排序的结构,则ArrayList
可能会更好,或者可能是插入所有元素后显式sort
的普通旧private fun getStoreCouponData() {
val userObservable = repo2
.create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
.getCoupons
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
val eventsObservable = repo2
.create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
.storeInfo
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
val combined = Observable.zip<StoreCoupons, StoreCoupons, StoreList>(userObservable, eventsObservable,
BiFunction<StoreCoupons, StoreCoupons, StoreList> { response1, response2 -> StoreList(response1, response2) })
combined.subscribe(object : DefaultObserver<StoreList>() {
override fun onNext(s: StoreList) {
for (item in s.store!!.coupons!!) {
System.out.println(item.store)
}
}
override fun onError(e: Throwable) {
System.out.println(e)
}
override fun onComplete() {
}
})
println(combined)
}
。