Java Java Data Structures Exploring the Java Collection Framework Sets

Phoenix S.
Phoenix S.
2,456 Points

Need assistance with 'for' loop for Set problem

My main issue is naming things correctly... I seem to keep coming up on this error no matter how many times I name and re-name the variables. Can someone explain to me WHY things need to be named the way they do.... for these problems

./com/example/BlogPost.java:69: error: cannot find symbol
   for (BlogPost authors : author) {
                           ^
  symbol:   variable author
  location: class BlogPost
./com/example/BlogPost.java:70: error: non-static method getAuthor() cannot be referenced from a static context
     allAuthors.addAll(BlogPost.getAuthor());
                               ^
./com/example/BlogPost.java:70: error: no suitable method found for addAll(String)
     allAuthors.addAll(BlogPost.getAuthor());
               ^
    method Collection.addAll(Collection) is not applicable
      (argument mismatch; String cannot be converted to Collection)
    method Set.addAll(Collection) is not applicable
      (argument mismatch; String cannot be converted to Collection)
Note: JavaTester.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
3 errors

1 Answer

Bob Allan
Bob Allan
10,899 Points

In Java, I read aloud my for-in loop like this - "for each element in whatever". This simplifies naming greatly.

So, the for loop above is backwards, if you read it aloud to yourself. It should be "for each author in authors", right?

for (BlogPost author : authors)...

This is a style point, but I prefer to write it like this, always using 'el', so I never confuse the name of the list with the element. You will encounter 'el' frequently for the element in for-each loops.

for (BlogPost el : authors)...