Java Java Data Structures Exploring the Java Collection Framework Sets

Jan Kalasnikov
Jan Kalasnikov
7,167 Points

mPosts problem in for-each loop

Hey guys, anyone knows why I have compile error for mPosts in the for-each loop? Thanks!

com/example/BlogPost.java
package com.example;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.HashSet; 
import java.util.TreeSet; 
import java.util.Set; 


public class BlogPost implements Comparable<BlogPost>, Serializable {
  private String mAuthor;
  private String mTitle;
  private String mBody;
  private String mCategory;
  private Date mCreationDate;

  public BlogPost(String author, String title, String body, String category, Date creationDate) {
    mAuthor = author;
    mTitle = title;
    mBody = body;
    mCategory = category;
    mCreationDate = creationDate;
  }

  public int compareTo(BlogPost other) {
    if (equals(other)) {
      return 0;
    }
    return mCreationDate.compareTo(other.mCreationDate);
  }

  public String[] getWords() {
    return mBody.split("\\s+");
  }

  public List<String> getExternalLinks() {
    List<String> links = new ArrayList<String>();
    for (String word : getWords()) {
      if (word.startsWith("http")) {
        links.add(word);
      }
    }
    return links;
  }

  public String getAuthor() {
    return mAuthor;
  }

  public String getTitle() {
    return mTitle;
  }

  public String getBody() {
    return mBody;
  }

  public String getCategory() {
    return mCategory;
  }

  public Date getCreationDate() {
    return mCreationDate;
  }

  public Set<String> getAllAuthors() {
    Set <String> set = new TreeSet<String>();
    for (BlogPost authorName : mPosts) {
     set.add(authorName.getAuthor()); 
    }
    return set;
  }
}
com/example/Blog.java
package com.example;

import java.util.List;

public class Blog {
  List<BlogPost> mPosts;

  public Blog(List<BlogPost> posts) {
    mPosts = posts;
  }

  public List<BlogPost> getPosts() {
    return mPosts;
  }
}

3 Answers

Seth Kroger
Seth Kroger
56,350 Points

The code of your method looks ok but it is in the wrong class. If you look at the top of the BlogPost class where you put it you'll see there is no field called mPosts. Since the method is supposed to answer a question about all the posts in a blog, not just a single post, it should be in the Blog class.

Jan Kalasnikov
Jan Kalasnikov
7,167 Points

Ohhhh yeaaah right, such a stupid mistake, thanks Seth!

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,777 Points

import java.util.Set; import java.util.TreeSet; public Set<String> getAllAuthors (){

Set<String >authorsSet = new TreeSet<>();

for(BlogPost post: mPosts){

authorsSet.add(post.getAuthor());
}

return authorsSet;

}