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

Creating BubbleSort

Now, we can start creating the bubble sort that implements the Sort interface:

package packt.java9.by.example.ch03.bubble; 

import packt.java9.by.example.ch03.*;
import java.util.Comparator;

public class BubbleSort implements Sort {
@Override
public void sort(SortableCollection collection) {
int n = collection.size();
while (n > 1) {
for (int j = 0; j < n - 1; j++) {
if (comparator.compare(collection.get(j),
collection.get(j + 1)) > 0) {
swapper.swap(j, j + 1);
}
}
n--;
}
}

Normally, the algorithm to execute needs two operations that we implemented in the code last time specific to a String array: comparing two elements and swapping two elements. As this time the sort implementation itself does not know what type the elements are used and also does not know if the something it sorts is an array, a lists or something else, it needs something that does it for the sort when needed. More precisely, it needs a comparator object capable of comparing two elements and it needs a swapper object that is capable of swapping two elements in the collection.

To get those, we can implement two setter methods that can set the objects for the purpose before sort is invoked. As this is not specific to the bubble sort algorithm but is rather general, these two methods should also be made a part of the interface, so the implementation is overriding it.

    private Comparator comparator = null; 

@Override
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}

private Swapper swapper = null;

@Override
public void setSwapper(Swapper swapper) {
this.swapper = swapper;
}
}

The @Override annotation signals for the Java compiler that the method is overriding a method of the parent class, or, as in this case, of the interface. A method can override a parent method without this annotation; however, if we use the annotation, the compilation fails if the method does actually not override something. This helps you discover during compile time that something was changed in the parent class or in the interface and we did not follow that change in the implementation, or that we just made some mistake thinking that we will override a method when we actually do not. As annotations are heavily used in unit tests, we will talk about annotations in a bit more detail later.

主站蜘蛛池模板: 保靖县| 饶平县| 上思县| 庆元县| 桦甸市| 财经| 虞城县| 涟水县| 梅河口市| 新疆| 宁明县| 乌拉特中旗| 鄂托克旗| 嵩明县| 绍兴县| 南投市| 宁津县| 正安县| 洪洞县| 佛冈县| 五原县| 上思县| 隆子县| 突泉县| 中牟县| 永州市| 高唐县| 松阳县| 肇源县| 竹山县| 金堂县| 渭源县| 新源县| 巴彦淖尔市| 凉山| 阳曲县| 宁晋县| 开远市| 光山县| 临泉县| 江都市|