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 trialEnyang Mercy
Courses Plus Student 2,339 PointsDesigning UI Fix the addTag and addTags
Stuck !!!! could you please help with correct code.
package com.example.model;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
public class Course {
private String mTitle;
private Set<String> mTags;
public Course(String title) {
mTitle = title;
mTags = new HashSet();
// TODO: initialize the set mTags
}
public void addTag(String tag) {
mTags.add(String tag);
// TODO: add the tag
}
public void addTags(List<String> tags) {
for (List<String>, List()) {
mTags.add(List<String>);
// TODO: add all the tags passed in
}
public boolean hasTag(String tag) {
// TODO: Return whether or not the tag has been added
return false;
}
public String getTitle() {
return mTitle;
}
}
4 Answers
Steve Hunter
57,712 PointsHi there,
In addTag
, don't redeclare the tag
as a string - it is only done once, in the method signature:
public void addTag(String tag) {
mTags.add(tag);
}
In the addTags
method, take the passed-in list and loop over it, pulling out each tag at a time. The list is made of strings, so define a new string local variable to hold each element of the list. Then pass that tag
to the addTag
method above:
for(String tag : tags){
// call the above method and pass in 'tag'
}
The comment directs the final line of code.
Let me know how you get on.
Steve.
Enyang Mercy
Courses Plus Student 2,339 PointsI couldn't compile. I'm stuck again
for(String tag : tags) {
String tag = new String(tag); string variable
mTags.addTag(tag)
Steve Hunter
57,712 PointsYou've done the for
loop correctly. Inside it just call addTag
and pass tag
to it. You can delete the String
line inside the loop - the new variable is created in the brackets of the for
loop; it is called tag
:
for(String tag : tags){
addTag(tag);
}
Steve.
Enyang Mercy
Courses Plus Student 2,339 PointsGot it!!!!!!!!!!!! Thank you
Seth Kroger
56,413 PointsSeth Kroger
56,413 PointsJust a quick comment that Lists do have an addAll() method that takes another collection, so you can skip the for loop and just use:
mtags.addAll(tags);
Some times a look at the docs can give you an easier way.
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsThat's a very good shout - thanks, Seth!