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 trialDavid Player
1,183 PointsHow 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
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
Bartosz Piechaczek
1,876 PointsJust 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
1,183 PointsI 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); }
David Player
1,183 PointsDavid Player
1,183 Pointspublic 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?
Bartosz Piechaczek
1,876 PointsBartosz Piechaczek
1,876 PointsYou 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.