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 - Retired Efficiency! Add tags to a course

David Player
David Player
1,183 Points

How to convert List to a HashSet?

I tried to pass List of tags in addTags method to a Set, but it asked me that it need to be converted so it can be passed and assigned to a mTags variable in addTags method. I googled and I couldn't discover an answer for my issue

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

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


public class Course {
  private String mTitle;
  private Set<String> mTags = new HashSet(); 


  public Course(String title) {
    mTitle = title;
    // TODO: initialize the set mTags
  }

  public void addTag(String tag) {
    // TODO: add the tag
  }

  public void addTags(List<String> tags) {
    // TODO: add all the tags passed in
   mTags.add(tags); 

  }

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

  public String getTitle() {
    return mTitle;
  }

}

2 Answers

Just use addAll() method on mTags and pass the list as an argument.

Let me know if something is not clear.

Hava a nice day!

David Player
David Player
1,183 Points

public void addTags(List<String> tags) { // TODO: add all the tags passed in mTags.addAll(tags);

} The error said that it is supposed to be able to add karaoke to an ArrayList of mTag variable, but it didn't added it. I'm not sure what's going on with this issue since this method is supposed to add all element to the the of this list?

You have initialized mTags in the declaration line. Do it in the constructor. It should look like this: mTags = new HashSet<>(); Then try again. Let me know if it works.

David Player
David Player
1,183 Points

I made a corrections, but it didn't able to add karaoke to an array of mTags

public Course(String title ) { mTitle = title; // TODO: initialize the set mTags mTags = new HashSet<>(); }

public void addTag(String tag) { // TODO: add the tag }

public void addTags(List<String> tags) { // TODO: add all the tags passed in mTags.addAll(tags); }