Testing the HashSet Class in Java

Problem:

Write a program that tests 10 of the 15 methods of HashSet class in java.

Output:

set.isEmpty(): true
[FR, US, RU, GB, CN]
set.size(): 5
set.contains("GB"): true
set.contains("JP"): false
set.isEmpty(): false
[FR, US, RU, BR, GB, CN]
[US, RU, BR, GB, CN]
US RU BR GB CN
[JP, FR, US, RU, GB, DE, IT, CA]
[US, RU, GB]
[BR, CN]
[US, RU, BR, GB, CN]
[]

Solution:

public class TestHashSet {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
System.out.printf("set.isEmpty(): %b%n", set.isEmpty());
Collections.addAll(set, "CN", "FR", "GB", "RU", "US");
System.out.println(set);
System.out.printf("set.size(): %d%n", set.size());
System.out.printf("set.contains(\"GB\"): %b%n", set.contains("GB"));
System.out.printf("set.contains(\"JP\"): %b%n", set.contains("JP"));
System.out.printf("set.isEmpty(): %b%n", set.isEmpty());
set.add("BR");
System.out.println(set);
set.remove("FR");
System.out.println(set);
String[] array = set.toArray(new String[0]);
for (String string : array) {
System.out.printf("%s ", string);
}
System.out.println("");
Set<String> g8 = new HashSet<String>();
Collections.addAll(g8, "CA", "DE", "FR", "GB", "IT", "JP", "RU", "US");
System.out.println(g8);
g8.retainAll(set);
System.out.println(g8);
set.removeAll(g8);
System.out.println(set);
set.addAll(g8);
System.out.println(set);
set.clear();
System.out.println(set);
}
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact