TreeSet
特點:
- 存儲數據屬於同一類型
- 存儲時按照自然排序
- 存儲自定義對象,1.自定義類要實現Comparable接口,重寫Comparable類2.制定一個比較器
//自帶排序
package chapter09;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args)
{
TreeSetDemo t=new TreeSetDemo();
t.TreeSetTest();
}
public void TreeSetTest()
{
Set set=new TreeSet();
set.add("yy");
set.add("dd");
set.add("hh");
for(Object obj:set)
{
System.out.println(obj);
}
}
}
//實現接口
package chapter09;
import java.util.Set;
import java.util.TreeSet;
public class PersonDemo1 implements Comparable{ //實現接口
private String name;
private Integer age;
//添加get|set方法快捷鍵 ALT+SHIFT+S+R
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//添加有參構造函數 快捷鍵 ALT+SHIFT+S+O
public PersonDemo1(String name, int age) {
super();
this.name = name;
this.age = age;
}
//添加構造函數 快捷鍵 ALT+SHIFT+S+C
public PersonDemo1() {
super();
// TODO Auto-generated constructor stub
}
//重寫CompareTo方法
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
PersonDemo1 p=(PersonDemo1)o;
int i= this.age.compareTo(p.age);
if(i==0)
{
return this.name.compareTo(p.name);
}
return i;
}
}
public class TreeSetDemo {
public static void main(String[] args)
{
TreeSetDemo t=new TreeSetDemo();
t.TreeSetTest();
}
public void TreeSetTest()
{
Set set=new TreeSet();
set.add(new PersonDemo1("zs",20));
set.add(new PersonDemo1("ls",20));
set.add(new PersonDemo1("ww",28));
for(Object obj:set)
{
PersonDemo1 p=(PersonDemo1)obj;
System.out.println(p.getName());
}
}
}
//制定比較器
package chapter09;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class PersonDemo1 {
private String name;
private Integer age;
//添加get|set方法快捷鍵 ALT+SHIFT+S+R
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//添加有參構造函數 快捷鍵 ALT+SHIFT+S+O
public PersonDemo1(String name, int age) {
super();
this.name = name;
this.age = age;
}
//添加構造函數 快捷鍵 ALT+SHIFT+S+C
public PersonDemo1() {
super();
// TODO Auto-generated constructor stub
}
}
public class TreeSetDemo {
public static void main(String[] args)
{
TreeSetDemo t=new TreeSetDemo();
t.TreeSetTest();
}
public void TreeSetTest()
{
//制定一個比較器
Mycomparator mc=new Mycomparator();
Set set=new TreeSet(mc); //傳入比較規則
set.add(new PersonDemo1("zs",20));
set.add(new PersonDemo1("ls",20));
set.add(new PersonDemo1("ww",20));
for(Object obj:set)
{
PersonDemo1 p=(PersonDemo1)obj;
System.out.println(p.getName());
}
}
}
class Mycomparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
PersonDemo1 p1=(PersonDemo1)o1;
PersonDemo1 p2=(PersonDemo1)o2;
int i=p1.getAge().compareTo(p2.getAge());
if(i==0)
{
return p1.getName().compareTo(p2.getName());
}
return i;
}
}