我自己尝试实现了,但是很别扭,感觉不通常,有没有人交流下
- package blog9;
- import java.util.TreeSet;
- /**
- * 泛型使用实例:
- * 1、定义一个表示点的类,包含横坐标和纵坐标值,且值具有三种形式,string、Integer、double。
- * 2、通过实现带泛型的comparable接口排序
- * 难题:如何让Point<T>实现comparable<T>接口,因为这里带了泛型,那么TreeSet的自然排序如何实现
- */
- public class TestGeneric {
- public static void main(String[] args) {
- //坐标为String类型
- TreeSet<Point<String>> spSet = new TreeSet<Point<String>>();
- spSet.add(new Point<String>("10","20"));
- spSet.add(new Point<String>("5","30"));
- spSet.add(new Point<String>("100","20"));
- System.out.println(spSet);
- //输出:[Point [x=5, y=30], Point [x=10, y=20], Point [x=100, y=20]]
-
- TreeSet<Point<Integer>> ipSet = new TreeSet<Point<Integer>>();
- ipSet.add(new Point<Integer>(40,60));
- ipSet.add(new Point<Integer>(20,60));
- ipSet.add(new Point<Integer>(330,60));
- ipSet.add(new Point<Integer>(5,60));
- System.out.println(ipSet);
- //输出:[Point [x=5, y=60], Point [x=20, y=60], Point [x=40, y=60], Point [x=330, y=60]]
-
- TreeSet<Point<Double>> dpSet = new TreeSet<Point<Double>>();
- dpSet.add(new Point<Double>(5.5,62.1));
- dpSet.add(new Point<Double>(200.5,30.54));
- dpSet.add(new Point<Double>(0.7,6.0));
- dpSet.add(new Point<Double>(500.54,20.4));
- System.out.println(dpSet); //这里是以y升序的,在compareTo方法中实现
- //[Point [x=0.7, y=6.0], Point [x=500.54, y=20.4], Point [x=200.5, y=30.54], Point [x=5.5, y=62.1]]
- }
- }
- class Point<T> implements Comparable<Point<T>>{
- private T x;
- private T y;
-
- public Point(T x,T y) {
- this.x = x;
- this.y = y;
- }
-
- @Override
- public String toString() {
- return "Point [x=" + x + ", y=" + y + "]";
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((x == null) ? 0 : x.hashCode());
- result = prime * result + ((y == null) ? 0 : y.hashCode());
- return result;
- }
- @SuppressWarnings("rawtypes")
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Point other = (Point) obj;
- if (x == null) {
- if (other.x != null)
- return false;
- } else if (!x.equals(other.x))
- return false;
- if (y == null) {
- if (other.y != null)
- return false;
- } else if (!y.equals(other.y))
- return false;
- return true;
- }
- @Override
- public int compareTo(Point<T> o) {
- if(o.x instanceof String){
- String s = (String)this.x;
- return Integer.parseInt(s) - Integer.parseInt((String)o.x);
- //感觉好麻烦,两个强转,失去了泛型的意义了
- }
- if(o.x instanceof Integer){
- Integer i = (Integer)this.x;
- return i.compareTo((Integer)o.x);
- }
- if(o.x instanceof Double){//当Point的类型为double时,用y值排序
- Double d = (Double)this.y;
- return d.compareTo((Double)o.y);
- }
- return 0;
- }
- }
复制代码
|