排序不同类型的对象(性能)

Wil*_*lco 0 java sorting performance

假设我有一个名为Unit的类(带位置变量x)并将类扩展为UnitA,UnitB,UnitC等.

这是我提出的:

Unit[] ordered = new Unit[a_num+b_num+c_num];
ordered = Arrays.copyOf(a_units, a_num); //and add b_units, c_units, etc
Arrays.sort(ordered); //sort using compareTo method
Run Code Online (Sandbox Code Playgroud)
  • 为了获得最佳性能和整洁的编程,从左到右(x变量)对这些值进行排序的最佳方法是什么?
  • 对数组进行排序时,为了访问单元特定的变量,如何找出每个条目的对象类型?

duf*_*ymo 5

如果您必须找出每个条目的对象类型,那么您做错了.

多态性是唯一的出路.这就是面向对象语言的用途.

You don't say how you want to sort units. Do you mean physical units, like meters for length, kilograms for mass, seconds for time? If yes, what does "sorting" them mean? You can order them alphabetically, of course, but I don't know how meaningful that is.

What is the "position variable"? Do you mean that you'll have a Unit for lengths with underlying values like meter, foot, angstrom, and furlong in different "positions"? And how will you order them? By popularity? The answer changes depending on whether you're in one of the few countries left that still use British units (e.g. the United States; even England gave up imperial units!) or metric.