- 論壇徽章:
- 0
|
問題描述:現(xiàn)有一些客戶數(shù)據(jù)要做統(tǒng)計篩選,設計用TreeSet來裝載數(shù)據(jù)。將客戶數(shù)據(jù)放入樹中,對客戶金額排序,當遇到客戶號相同時,插入樹時,將余額相加!代碼如下:
先設計一個節(jié)點類(filenam:TradeNode.java):import java.util.Comparator;
public class TradeNode implements Comparable<TradeNode> {
private String cstm; // 客戶號
private Integer mon = 0; // 交易金額
public TradeNode(String cstm, int mon) {
this.mon = mon;
this.cstm = cstm;
}
public int compareTo(TradeNode o) {
if (o.cstm.equals(this.cstm)) {
o.mon += this.mon;
return 0;
} else if (this.mon == o.mon) {
return this.cstm.compareTo(o.cstm);
} else {
return (o.mon - this.mon);
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "[" + cstm + "] [" + mon + "]";
}
public int getMon() {
return mon;
}
public void setMon(Integer mon) {
this.mon = mon;
}
public String getCstm() {
return cstm;
}
} |
然后繼承了TreeSet重寫了add函數(shù)(filename:LsTree.java):import java.util.TreeSet;
public class LsTree extends TreeSet<TradeNode> {
// 添加子節(jié)點
public boolean add(TradeNode node) {
// System.out.println("add node="+node);
if (contains(node)) {
return true;
}
return super.add(node);
}
}
|
測試(filename:testtree2.java:public class testtree2 {
public static void main(String[] args) {
TradeNode nd1 = new TradeNode("44010358010481", 150354);
TradeNode nd2 = new TradeNode("44010358010481", 150641);
TradeNode nd3 = new TradeNode("44010358010481", 270000);
TradeNode nd4 = new TradeNode("44010039275685", 10000);
TradeNode nd5 = new TradeNode("44010039275685", 980000);
TradeNode nd6 = new TradeNode("44010039275685", 5000);
LsTree tree = new LsTree();
tree.add(nd1);
tree.add(nd2);
tree.add(nd3);
tree.add(nd4);
tree.add(nd5);
tree.add(nd6);
for (TradeNode node : tree) {
System.out.println(node);
}
}
} |
得到的結(jié)果:[44010039275685] [980000]
[44010358010481] [570995]
[44010039275685] [15000] |
按我的想法,該樹應該只有兩個節(jié)點,可是輸出卻是3個節(jié)點,左思右想不明白,測試數(shù)據(jù)修改后有時又能得到正確的結(jié)果。剛學習java沒多久,請大家?guī)兔纯矗≈x謝! |
|