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! Design the UI

Tomas Verblya
Tomas Verblya
1,998 Points

Problem with the objective.

So I can't seem to be able to figure out how to initialize a set in the constructor.

It wants me to initialize mTags in the constructor. "I've added the private set mTags. For the first task, can you please initialize it in the Constructor."

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;

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

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

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

  public void addTags(List<String> tags) {
    // 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;
  }

}

Basically I tried to add it in the constructor that was available, (with the title passed in), and I even made a new one with no parameters.

Pressing check work prompts me if I initialized the set mTags in the constructor.

2 Answers

Florian Tönjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

Hi Tomas,

the mTags Set is already defined as a field of the class. All you need is to import the HashSet<String> and then add this line to the constructor:

mTags = new HashSet<String>();

You don't need to define it with "Set<String>" again.

Kind Regards, Florian

Tomas Verblya
Tomas Verblya
1,998 Points

Thank you so much!!!!!!!! Clumsy of me. But then why would it compile?

Florian Tönjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

It compiled because there was no syntax error.

By defining mTags with "Set<String>" again, you overwrote the access to the mTags field of the class. So instead of assigning to the class field you assign to a local variable with method scope, that's why the challenge wouldn't pass, the mTags field did not get initialized, only a method local mTags variable in the constructor.