Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,481 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.