user98643
user98643

Reputation: 33

Error: incompatible types (for sets)

Is there a such thing as casting Sets?

I have a constructor that takes Set<String> things as a parameter, and I would like to set a field TreeSet<String> stuff to be this initial set of things. However, I keep getting an error. Java is not liking my statment

stuff = things;

So I am wondering if putting all elements of things into a list and then moving the elements of that list into stuff is a good solution, or if there is a better way.

Here is what I've come up with:

public class Anagrams {
   private TreeSet<String> allWords;  

   //pre: the given dictionary must be in alphabetical order, if null throws an 
   //  illegalArgumentException
   //post: creates a new anagram solver
   public Anagrams(Set<String> dictionary) {
      if(dictionary == null) {
         throw new IllegalArgumentException();
      }
      for(String word : dictionary){
         String temp = word;
         allWords.add(word);
      }     
   }

Upvotes: 0

Views: 940

Answers (2)

vandale
vandale

Reputation: 3650

it is because TreeSet is a child of Set so you cannot asign a set to a tree set (the other way is possible)

so you'd need to cast explicitly (provided things is a TreeSet<String>:

stuff = (TreeSet<String>) things;

Upvotes: 0

pobrelkey
pobrelkey

Reputation: 5973

Instantiate a new TreeSet<String> by populating it from things:

stuff = new TreeSet<String>(things);

Upvotes: 2

Related Questions