TreeSet與HashSet之間的差別:
TreeSet會自動按自然排序法給元素排序,相應的性能會差一點。而HashSet是根據元素的hashCode自動給元素排序的,如果我們不需要使用排序功能,則應該使用HashSet。
相應的使用TreeSet的對象需要實作Comparable接口,并重寫compareTo方法。
package com.test;
public class T implements Comparable<T>{
private int t_id;
private String t_name;
T(int id,String name) {
this.setT_id(id);
this.setT_name(name);
}
public int getT_id() {
return t_id;
}
public void setT_id(int t_id) {
this.t_id = t_id;
}
public String getT_name() {
return t_name;
}
public void setT_name(String t_name) {
this.t_name = t_name;
}
public int compareTo(T o) {
if (this.getT_id()<o.getT_id()) {
return -1;
}if (this.getT_id()>o.getT_id()) {
return 1;
}else {
//如果t_id相等的話就無法添加
return 0;
}
}
}
[size=large][color=red][b]合并重複資料:
[/b][/color][/size]當出現重複資料時不添加,但是在更改重複資料的内容-類似于網購:如果你添加相同的訂單,它隻會在數量上加1而不是添加多一條記錄(個人了解,至于真正的網購是怎麼處理的我也不清楚)。
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class T implements Comparable<T>{
private int t_id;
private int t_num;
private String t_name;
T(){
}
T(int id,int num,String name) {
this.setT_id(id);
this.setT_num(num);
this.setT_name(name);
}
public int getT_id() {
return t_id;
}
public void setT_id(int t_id) {
this.t_id = t_id;
}
public int getT_num() {
return t_num;
}
public void setT_num(int t_num) {
this.t_num = t_num;
}
public String getT_name() {
return t_name;
}
public void setT_name(String t_name) {
this.t_name = t_name;
}
public int compareTo(T o) {
if (this.getT_name().equals(o.getT_name())) {
//重複不添加,隻修改其中的num值--o為set中存在的對象
o.setT_num((this.getT_num())+o.getT_num());
return 0;
}else {
//固有排序
if (this.getT_id()<o.getT_id()) {
return -1;
}
if (this.getT_id()>o.getT_id()) {
return 1;
}
else {
//如果t_id相等的話就無法添加
return 0;
}
}
}
public static void main(String[] args) {
T t0=new T(0,1,"t0000");
T t1=new T(1,1,"t1111");
T t2=new T(2,1,"t2222");
T t2_add=new T(2,9,"t2222");
Set<T> set=new TreeSet();
set.add(t0);
set.add(t1);
set.add(t2);
set.add(t2_add);
System.out.println(set.size());
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
T t = (T) iterator.next();
System.out.println("value="+"---"+t.getT_id()+"---"+"數量:"+t.getT_num()+"---"+t.getT_name());
}
}
}
輸出結果:
3
value=---0---數量:1---t0000
value=---1---數量:1---t1111
value=---2---數量:10---t2222 //原來數量為1的,後來加了一條數量為9的資料