Java Java Data Structures Efficiency! Add tags to a course

Herman Vicens
Herman Vicens
12,540 Points

Error moving elements from a List to a Set.

I am trying to move the elements of a List to a Set and I get this error:

java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) at java.util.AbstractCollection.addAll(AbstractCollection.java:344) at com.example.model.Course.addTags(Course.java:23) at JavaTester.run(JavaTester.java:96) at JavaTester.main(JavaTester.java:43)

Is there any other way to accomplish this move?

com/example/model/Course.java
package com.example.model;

import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

public class Course {
  private String mTitle;
  private Set<String> mTags;

  public Course(String title) {
    mTitle = title;
    mTags = new HashSet<String>();
  }

  public void addTag(String tag) {
    mTags.add(tag);
  }

  public void addTags(List<String> tags) {
     tags.addAll(mTags) ;  //Copy all elements of a List<String> to a HashSet<String>
  }

  public boolean hasTag(String tag) {
    // TODO: Return whether or not the tag has been added
    return false;
  }

  public String getTitle() {
    return mTitle;
  }

}

2 Answers

jose rodriguez
jose rodriguez
16,524 Points

your code has tags.addAll(mTags);

its should be mTags.addAll(tags);

Anders Björkland
Anders Björkland
7,480 Points

Hi Herman,
It appears you are trying to add a Set to the List parameter that is in your addTags-method, instead of the other way around.