Compare different object types with comparator

前端 未结 2 812
有刺的猬
有刺的猬 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 06:48

    If you store objects of the two unrelated types in a Set (which makes me wonder, since Sets are usually unordered), this means you are using a raw Set, which is not very type safe.

    You can define an interface CommonAB that contains getter methods for all the common properties of A and B. Both A and B will implement that interface. You'll be able to put instances of A and B in a Set.

    Finally, a Comparator will be able to compare objects of both types. The Comparator will access only the methods of the interface. It won't care if it's comparing two As, two Bs or an A and a B.

提交回复
热议问题