0

So for a project, I have to sort words in alphabetical order that are encapsulated within a Word class that implements Comparable. The instances of Word are to be sorted within an ArrayList from a separate, static class containing the algorithm. I have created a standard selection sort algorithm that acts on instances of objects implementing the Comparable interface, but in my main class it throws an error whenever I try to pass an ArrayList< Word >. I noticed that if I change the type to ArrayList< Comparable > then it works, but I feel as if this isn't the greatest convention as it will only hold Word objects. Am I doing anything wrong, and if so, what can I do to fix this?

I'll attach the code that I feel is necessary to visualize what I mean

Declaration and instantiation of the ArrayList:

private static ArrayList<Word> words;
words = new ArrayList<Word>();

Line in question that throws an error :

ObjectALSelectionSort.selectionSort(words);

Header for the Word class:

public class Word implements Comparable<Word>

Header for the selectionSort() method:

public static void selectionSort(ArrayList<Comparable> list)

I guess what really confuses me is as to why I'm not able to pass an ArrayList of objects that implement Comparable to a method that acts on Comparables.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
zebra14420
  • 51
  • 1
  • 2
  • 7

0 Answers0