- package cn.javastudy.p3.Collection.copy;
- import java.awt.peer.SystemTrayPeer;
- import java.util.*;
- @SuppressWarnings("unused")
- public class MyVector3 {
- public static void main(String[] args)
- {
- MyComparator com=new MyComparator();
- TreeSet<myInteger> v=new TreeSet<myInteger>(com);
- //向ArrayList中添加元素
- v.add(new myInteger(10));
- v.add(new myInteger(40));
- v.add(new myInteger(20));
- v.add(new myInteger(50));
- v.add(new myInteger(50));
- Iterator<myInteger> it=v.iterator();
- while(it.hasNext())
- System.out.println(it.next().getIt());
- }
- }
- class myInteger extends abc
- {
- public Integer getIt() {
- return it;
- }
- public myInteger(Integer it) {
- this.it = it;
- }
- public boolean equals(Object obj) {
- return it.equals(((myInteger)obj).it);
- }
-
-
- }
- class abc
- {
- Integer it=null;
- }
- class MyComparator implements Comparator<abc>
- {
- @Override
- public int compare(abc o1, abc o2) {
- if(o1.equals(o2))
- return 0;
- return o1.it<o2.it?-1:1;
- }
- }
- /*
- 10
- 20
- 40
- 50
- */
复制代码 不重写如下
- package cn.javastudy.p3.Collection.copy;
- import java.awt.peer.SystemTrayPeer;
- import java.util.*;
- @SuppressWarnings("unused")
- public class MyVector3 {
- public static void main(String[] args)
- {
- MyComparator com=new MyComparator();
- TreeSet<myInteger> v=new TreeSet<myInteger>(com);
- //向ArrayList中添加元素
- v.add(new myInteger(10));
- v.add(new myInteger(40));
- v.add(new myInteger(20));
- v.add(new myInteger(50));
- v.add(new myInteger(50));
- Iterator<myInteger> it=v.iterator();
- while(it.hasNext())
- System.out.println(it.next().getIt());
- }
- }
- class myInteger extends abc
- {
- public Integer getIt() {
- return it;
- }
- public myInteger(Integer it) {
- this.it = it;
- }
- // public boolean equals(Object obj) {
- // return it.equals(((myInteger)obj).it);
- // }
-
-
- }
- class abc
- {
- Integer it=null;
- }
- class MyComparator implements Comparator<abc>
- {
- @Override
- public int compare(abc o1, abc o2) {
- if(o1.equals(o2))
- return 0;
- return o1.it<o2.it?-1:1;
- }
- }
复制代码 使用TreeSet存贮对像时,还得重写对像的equals方法,不重写的话,有重复的元素 |