I have to implement a method which sorts any kind of collection by using bubble sort and after that to test if it really is sorted how can I accomplish this by using generics ?
This is what i've done so far :
public class SortManager {
public <T extends Collection> void bubbleSort(T collection) {
//sort a given collection
}
public <T extends Collection<?>> boolean isSorted(T collection) {
//need to check if a given collection is sorted
return false;
}
}
And the test:
@Test
public void testIfTheCollectionsAreSorted() {
ArrayList<Integer> integers = new ArrayList<>();
SortManager sortManager = new SortManager();
sortManager.bubbleSort(integers);
assertTrue(sortManager.isSorted(integers));
}
You can not sort any given collection, because not all collections are ordered. However, you can sort any List<...>
Bubble sort is easily looked up and implemented, what you missed here is that the elements must implement Comparable<...>
or change the signature to take a comparator (but you probably want the latter)
class SortManager {
public <T> void bubbleSort(List<T> list, Comparator<? super T> comp) {
...
}
public <T> boolean isSorted(List<T> list, Comparator<? super T> comp) {
...
return false;
}
}