我正在尝试通过读取文件并计算每个字母空格符号的频率等来创建霍夫曼树。我正在使用优先队列将项目从最小到最大排队但是当我将它们插入队列时它们没有正确排队这是我的代码。包霍夫曼;
导入 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() 方法中是我遇到问题的地方。我试图做的是队列频率对象,其中包含字母/空格/符号和频率作为频率类是这样的。公共类频率实现 Comparable { private String s; 私人诠释 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;
}
}
我怎样才能让优先队列使用频率数将它们从最小到最大排队?