gpt4 book ai didi

java - 哈夫曼树优先队列

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:05 25 4
gpt4 key购买 nike

我正在尝试通过读取文件并计算每个字母空格符号等的频率来创建霍夫曼树。我正在使用 Priorityqueue 将项目从最小到最大排队,但是当我将它们插入队列时,它们不要正确排队这是我的代码。 包装霍夫曼;

导入java.io.FileNotFoundException;导入 java.io.FileReader;导入 java.util.ArrayList;导入 java.util.PriorityQueue;导入 java.util.Scanner;

公开课哈夫曼{

public ArrayList<Frequency> fileReader(String file)
{
ArrayList<Frequency> al = new ArrayList<Frequency>();
Scanner s;
try {

s = new Scanner(new FileReader(file)).useDelimiter("");
while (s.hasNext())
{
boolean found = false;
int i = 0;
String temp = s.next();
while(!found)
{


if(al.size() == i && !found)
{
found = true;
al.add(new Frequency(temp, 1));
}
else if(temp.equals(al.get(i).getString()))
{
int tempNum = al.get(i).getFreq() + 1;
al.get(i).setFreq(tempNum);
found = true;
}
i++;

}



}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return al;
}
public void buildTree(ArrayList<Frequency> al)
{
PriorityQueue<Frequency> pq = new PriorityQueue<Frequency>();
for(int i = 0; i < al.size(); i++)
{
pq.add(al.get(i));
}
while(pq.size() > 0)
{
System.out.println(pq.remove().getString());
}
}
public void printFreq(ArrayList<Frequency> al)
{
for(int i = 0; i < al.size(); i++)
{
System.out.println(al.get(i).getString() + "; " + al.get(i).getFreq());
}
}

buildTree() 方法是我遇到问题的地方。我想做的是将包含字母/空格/符号和频率的频率对象排队,频率类就是这个。 公共(public)类频率实现 Comparable { 私有(private)字符串; 私有(private)整数 n;

Frequency(String s, int n)
{
this.s = s;
this.n = n;
}
public String getString()
{
return s;
}
public int getFreq()
{
return n;
}
public void setFreq(int n)
{
this.n = n;
}
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}

如何让优先级队列使用频率编号将它们从小到大排入队列?

最佳答案

实际上您错过了实现 compareTo使您的对象有效地具有可比性的方法。

compareTo方法,如文档所述,应该

return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

这意味着在您的情况下,您应该执行以下操作:

public int compareTo(Object arg0)
{
Frequency other = (Frequency)arg0;

return n < other.n ? -1 : (n == other.n ? 0 : 1);
}

但请注意,comparable 有一个更可取的通用类型:Comparable<T>这样你就可以避免对 arg0 进行强制转换使其成为 Frequency也具有静态类型安全的对象:

class Frequency implements Comparable<Frequency> {   
public int compareTo(Frequency f2) {
// directly compare
}
}

关于java - 哈夫曼树优先队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305013/

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