Compare different object types with comparator

前端 未结 2 787
有刺的猬
有刺的猬 2021-01-06 06:10

I need to write a Comparator that take an object A of type A and an object B of type B. The two object are not an extention of a common object. They are really diffferent, b

2条回答
  •  醉梦人生
    2021-01-06 07:00

    There's a very hacky way of doing it that allows you to use Object and instanceof but if you can implement a proxy class that exposes a specific interface you would be better off doing that.

    class A {
    
        public String getSomething() {
            return "A";
        }
    }
    
    class B {
    
        public String getSomethingElse() {
            return "B";
        }
    }
    
    class C implements Comparator {
    
        @Override
        public int compare(Object o1, Object o2) {
            // Which is of what type?
            A a1 = o1 instanceof A ? (A) o1: null;
            A a2 = o2 instanceof A ? (A) o2: null;
            B b1 = o1 instanceof B ? (B) o1: null;
            B b2 = o2 instanceof B ? (B) o2: null;
            // Pull out their values.
            String s1 = a1 != null ? a1.getSomething(): b1 != null ? b1.getSomethingElse(): null;
            String s2 = a2 != null ? a2.getSomething(): b2 != null ? b2.getSomethingElse(): null;
            // Compare them.
            return s1 != null ? s1.compareTo(s2): 0;
        }
    
    }
    
    
    

    The more acceptable mechanism would be to implement a proxy class for each that implements a common interface tyhat can then be compared using a proper type-safe comparator.

    interface P {
    
        public String getValue();
    }
    
    class PA implements P {
    
        private final A a;
    
        PA(A a) {
            this.a = a;
        }
    
        @Override
        public String getValue() {
            return a.getSomething();
        }
    }
    
    class PB implements P {
    
        private final B b;
    
        PB(B b) {
            this.b = b;
        }
    
        @Override
        public String getValue() {
            return b.getSomethingElse();
        }
    }
    
    class PC implements Comparator

    { @Override public int compare(P o1, P o2) { return o1.getValue().compareTo(o2.getValue()); } }

    提交回复
    热议问题