Here are the expected results at each stage of this activity:
As a result of adding one item to the set, and then displaying the contents of the set, you should get this output:
[Persuasion]
As a result of adding a number of further items to the set, you may get this output:
[Sense and Sensibility, Northanger Abbey, Mansfield Park, Emma, Persuasion] 5
Removing the item "Northanger Abbey" could give the following output:
[Sense and Sensibility, Mansfield Park, Emma, Persuasion] 4
The set items may appear in a different order from this, because a HashSet implementation does not guarantee any particular order for its contents.
Using a TreeSet means that the display should show the same elements as before, but now in alphabetical order:
[Emma, Mansfield Park, Persuasion, Sense and Sensibility]
The key difference between a HashSet and a TreeSet is that the elements in a TreeSet are ordered, those of a HashSet are not.
The argument to a Set constructor can be another kind of collection, not necessarily a set. This is very useful because it lets us do things like convert a list to a set, which has the effect of removing any duplication amongst the items.
After removing all four elements from the set referenced by set2 the isEmpty method should return the value true and this is the expected output.
For reference, here is the complete code. We have indicated which section corresponds to each part of the question.
// Step 1
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
// Step 2
Set<String> set1;
set1 = new HashSet<String>();
set1.add("Persuasion");
System.out.println(set1);
// Step 3
set1.add("Mansfield Park");
set1.add("Northanger Abbey");
set1.add("Emma");
set1.add("Sense and Sensibility");
System.out.println(set1);
System.out.println(set1.size());
set1.remove("Northanger Abbey");
System.out.println(set1);
System.out.println(set1.size());
// Step 4
Set<String> set2 = new TreeSet<String>(set1);
System.out.println(set2);
// Step 5
set2.remove("Persuasion");
set2.remove("Mansfield Park");
set2.remove("Emma");
set2.remove("Sense and Sensibility");
System.out.println(set2.isEmpty());
}
}