Java Java Data Structures 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
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 42,398 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
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 42,398 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.