Alan Alan - 1 month ago 15
Java Question

How to use a for loop to print object values into a HashSet?

I am new to java and am doing a programming challenge and just can't seem to understand what is meant by:


  1. Uses two for loops to put all the words from this (remember, you will be executing this method inside a WordGroup object) and the parameter WordGroup into the HashSet.



(presume this refers to one of my WordGroups.)

I have seen other examples of for loops being used to to store objects, but I have never done this personally. I've only ever used a for loop to iterate through the an array list and print out a list of variables before. I'm not sure how I would write this for loop out to carry out this instruction. Here is the code:

WordGroup class

package lab5;
import java.util.HashSet;
public class WordGroup {

String word;

//Creates constructor which stores a string value in variable "word" and converts this into lower case using the lower case method.
public WordGroup(String aString) {
this.word = aString.toLowerCase();
}
public String[] getWordArray() {
String[] wordArray = word.split("-");
return wordArray;
}


public String getWordSet(WordGroup secondWordGroup) {

HashSet<String> newHashSet = new HashSet<>();

for (WordGroup x : secondWordGroup) {
newHashSet.put(x);
}

}
}


Main class

package lab5;

public class Main{
public static void main (String[] args) {
WordGroup firstWordGroup = new WordGroup("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");

System.out.println("*****First Array list*****");
String[] firstWordArray = firstWordGroup.getWordArray();
for( String word : firstWordArray) {
System.out.println(word);
}
System.out.println("*****Second Array list*****");
String[] secondWordArray = secondWordGroup.getWordArray();
for( String word : secondWordArray) {
System.out.println(word);
}
}
}


If anybody could help a beginner out on what is meant by this and how to implement this, that would be very helpful and much appreciated by myself and possibly others who may have the same issue. Thanks. P.S. I know my for loop is completely wrong but I wanted to at least attempt it rather than asking for help without actually trying myself.

Answer

It's a little bit unclear, but I'm assuming that getWordSet should return the set of words that are in both the WordGroup object that you call on, and the WordGroup that you give as input. So if wg1 has the words "a" and "b", and wg2 has the words "b" and "c", then wg1.getWordSet(wg2) returns the set containing the words "a", "b", "c".

To accomplish this, you will want to do something like this:

HashSet<String> newHashSet = new HashSet<>();
for (String word : secondWordGroup.getWordArray())
    newHashSet.add(word);

for (String word : this.getWordArray())
    newHashSet.add(word);