官术网_书友最值得收藏!

Amending the interfaces

The modified Sort interface will look like this:

public interface Sort { 
void sort(SortableCollection collection);
void setSwapper(Swapper swap);
void setComparator(Comparator compare);
}

This also means that we will need two new interfaces: Swapper and Comparator. We are lucky that the Java runtime already defines a Comparator interface that just fits the purpose. You may have guessed that from the following import statement:

import java.util.Comparator;

When you need something very basic, like a comparator interface, it is most probably defined in the runtime. It is advisable to consult the runtime before writing your own version. The Swapper interface, however, we will have to create.

package packt.java9.by.example.ch03; 

public interface Swapper {
void swap(int i, int j);
}

As it is used to swap two elements specified by the indices in SortableCollection, there is a method, quite trivially named swap for the purpose. But, we are not ready yet. If you try to compile the preceding code, the compiler will complain about the get and size methods. They are needed by the algorithm to implement the sort, but they are not inherently part of the sorting itself. This is a responsibility that should not be implemented in the sort. As we do not know what type of collections we will sort, it is not only unadvisable but also impossible to implement these functionalities inside the sort. It seems that we just cannot sort anything. There are some restrictions we will have to set. The sorting algorithm must know the size of the collection we sort and also should have access to an element by index so that it can pass it on to the comparator.

These restrictions are expressed in the SortableCollection interface that we just left empty not knowing before the first sort implementation what is required to be there.

package packt.java9.by.example.ch03; 

public interface SortableCollection {
Object get(int i);
int size();
}

Now, we are ready with the interfaces and the implementation and we can go on testing the code. But, before that, we will briefly reiterate what we did and why we did that.

主站蜘蛛池模板: 乐平市| 苍溪县| 攀枝花市| 霍林郭勒市| 扎囊县| 承德县| 宁城县| 深州市| 黄骅市| 大港区| 阿瓦提县| 巴彦县| 准格尔旗| 山丹县| 察雅县| 剑川县| 渝北区| 夏邑县| 分宜县| 临沭县| 文水县| 北京市| 泸水县| 伊春市| 措勤县| 余姚市| 惠水县| 石门县| 宁夏| 汤原县| 什邡市| 巍山| 莲花县| 额尔古纳市| 含山县| 南乐县| 台北县| 壶关县| 长兴县| 崇阳县| 玉林市|