如何对集合中的两个不同对象进行排序? [英] How to sort two different objects in a collection?

查看:162
本文介绍了如何对集合中的两个不同对象进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类CLassA和CLassB。并且它们有一个共同的属性,例如每个类所持有的元素数。

Suppose I have two classes CLassA and CLassB. And they have one atributte in common, for example the number of elements that each class holds.

如何从ClassA和CLassB的对象创建集合并按其排序属性(按降序递增,无关紧要)?

How can i create a collection from objects of ClassA and CLassB and sort by that attribute (ascending of descending order, doesn't matter)?

我创建了一个类型的集合,但是当我尝试实现Comparable Interface时,我无法访问方法(例如,获取返回元素的n)。

I made a collection of type but when I try to implement the Comparable Interface i can't acess to that method (a get that returns the nr of elements for example).

我有什么解决方案?

谢谢你的帮助!

推荐答案

真的,ClassA和ClassB应该通过继承层次结构相关联,或者通过公共接口相关联,如果你要将它们放在一起两个都在同一个集合中。

Really ClassA and ClassB should be related either through an inheritance hierarchy, or by a common interface if you are going to put them both in the same collection.

最简单的事情是拥有一个公共接口,为common属性提供一个访问器方法。然后比较器可以使用该方法(通过接口)从ClassA的实例以及ClassB的实例中获取值。

The simplest thing would be to have a common interface that provides an accessor method for the common attribute. And then the comparator could use that method (through the interface) for fetching the value from ClassA's instance as well as ClassB's instance.

这篇关于如何对集合中的两个不同对象进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆