Title: Hashset Java Example - Java Code Geeks
Open Graph Title: Hashset Java Example - Java Code Geeks
Description: 1. Introduction The HashSet class is a part of the Java Collection API since JDK 1.2. It extends from the AbstractSet class and implements the Set Java
Open Graph Description: 1. Introduction The HashSet class is a part of the Java Collection API since JDK 1.2. It extends from the AbstractSet class and implements the Set Java
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/hashset-java-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/hashset-java-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/"},"author":{"name":"Mary Zheng","@id":"https://examples.javacodegeeks.com/#/schema/person/8a2034fbabcb20a9396e9819261855ae"},"headline":"Hashset Java Example","datePublished":"2020-02-14T09:00:00+00:00","dateModified":"2022-07-06T10:26:20+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/"},"wordCount":566,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/hashset-java-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/hashset-java-example/","url":"https://examples.javacodegeeks.com/hashset-java-example/","name":"Hashset Java Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2020-02-14T09:00:00+00:00","dateModified":"2022-07-06T10:26:20+00:00","description":"1. Introduction The HashSet class is a part of the Java Collection API since JDK 1.2. It extends from the AbstractSet class and implements the Set Java","breadcrumb":{"@id":"https://examples.javacodegeeks.com/hashset-java-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/hashset-java-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/hashset-java-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/hashset-java-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"Hashset Java Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/8a2034fbabcb20a9396e9819261855ae","name":"Mary Zheng","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2017/11/Mary-Zheng_avatar_1510732235-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2017/11/Mary-Zheng_avatar_1510732235-96x96.jpg","caption":"Mary Zheng"},"description":"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.","url":"https://examples.javacodegeeks.com/author/mary-zheng/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2020-02-14T11:00:00+02:00","datePublished":"2020-02-14T11:00:00+02:00","dateModified":"2022-07-06T13:26:20+03:00","headline":"Hashset Java Example","name":"Hashset Java Example","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/hashset-java-example\/","description":"1. Introduction The HashSet class is a part of the Java Collection API since JDK 1.2. It extends from the AbstractSet class and implements the Set Java interface. It uses HashMap internally. Figure 1","copyrightYear":"2020","articleSection":"Core Java","articleBody":"\n1. Introduction\n\n\n\nThe HashSet class is a part of the Java Collection API since JDK 1.2. It extends from the AbstractSet class and implements the Set Java interface. It uses HashMap internally.\n\n\n\nFigure 1 HashSet\n\n\n\nYou can also check the Java Set Example in the following video:\n\n\n\n Java Set Example - Video\n\n\n\nThe HashSet class contains unique elements. It permits the null element. It does not maintain the insertion order and is not thread-safe. In this example, I will demonstrate the following items:\n\n\n\nHow to create a HashSet objectHow to read, add, remove, and iterate elements in a HashSetCompare HashSet to TreeSetCompare HashSet to LinkedHashSet\n\n\n\n2. Technologies Used\n\n\n\nThe example code in this article was built and run using:\n\n\n\nJava 11Maven 3.3.9Eclipse OxygenJunit 4.12\n\n\n\n3. Maven Project\n\n\n\n3.1 Dependencies\n\n\n\nI will include Junit in the pom.xml.\n\n\n\n<project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\"\n\txmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n\txsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0<\/modelVersion>\n\t<groupId>jcg.zheng.demo<\/groupId>\n\t<artifactId>java-hashset-demo<\/artifactId>\n\t<version>0.0.1-SNAPSHOT<\/version>\n\t<build>\n\t\t<sourceDirectory>src<\/sourceDirectory>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin<\/artifactId>\n\t\t\t\t<version>3.8.0<\/version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<release>11<\/release>\n\t\t\t\t<\/configuration>\n\t\t\t<\/plugin>\n\t\t<\/plugins>\n\t<\/build>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit<\/groupId>\n\t\t\t<artifactId>junit<\/artifactId>\n\t\t\t<version>4.12<\/version>\n\t\t<\/dependency>\n\t<\/dependencies>\n<\/project>\n\n\n\n4. JUnit Test\n\n\n\n4.1 How to Construct HashSet\n\n\n\nThe HashSet class has four constructors:\n\n\n\nHashSet() - Constructs a new empty set with default initial capacity (16) and load factor (0.75).HashSet\u200b(int initialCapacity) - Constructs a new empty set with the specified initial capacity and default load factor (0.75).HashSet\u200b(int initialCapacity, float loadFactor) - Constructs a new empty set with the specified initial capacity and the specified load factor.HashSet\u200b(Collection c) - Constructs a new set containing the elements in the specified collection.\n\n\n\nIn this step, I will show how to create a Hashset object via these four constructors. I emphasize the HashSet\u200b(Collection c) constructor with the following tests:\n\n\n\nvia_collection_list() - create a HashSet via a List objectvia_collection_set() - create a HashSet via a Set objectvia_stream() - create a HashSet via Stream.of\n\n\n\nHashSet_ConstructorTest.java \n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport org.junit.Test;\n\npublic class HashSet_ConstructorTest {\n\n\t@Test\n\tpublic void via_collection_list() {\n\t\tHashSet<String> fromAnotherCollection = new HashSet<>(Arrays.asList(\"Mary\", \"Zheng\"));\n\t\tassertFalse(fromAnotherCollection.isEmpty());\n\t\tassertTrue(fromAnotherCollection.contains(\"Mary\"));\n\t\tassertTrue(fromAnotherCollection.contains(\"Zheng\"));\n\t}\n\n\t@Test\n\tpublic void via_collection_set() {\n\t\tSet<String> fromCollectionUtils = Collections.singleton(\"Mary\");\n\t\tassertFalse(fromCollectionUtils.isEmpty());\n\t\tassertTrue(fromCollectionUtils.contains(\"Mary\"));\n\t}\n\n\t@Test\n\tpublic void via_default_constructor() {\n\t\t\/\/ Default initial capacity is 16\n\t\t\/\/ Default load factor is 0.75\n\t\tHashSet<String> createdByDefaultConstructor = new HashSet<>();\n\n\t\tassertTrue(createdByDefaultConstructor.isEmpty());\n\t}\n\t\n\n\t@Test\n\tpublic void via_initialCapacity_constructor() {\n\t\t\/\/ initial capacity is 0\n\t\t\/\/ Default load factor is 0.75\n\t\tHashSet<String> createdByDefaultConstructor = new HashSet<>(0);\n\n\t\tassertTrue(createdByDefaultConstructor.isEmpty());\n\t}\n\n\t@Test\n\tpublic void via_initialCapacity_loadfactor_constructor() {\n\t\t\/\/ initial capacity is 0\n\t\t\/\/ load factor is 1\n\t\tHashSet<String> createdByDefaultConstructor = new HashSet<>(0, 1);\n\n\t\tassertTrue(createdByDefaultConstructor.isEmpty());\n\t}\n\n\t@Test\n\tpublic void via_list() {\n\t\tList<String> listHasDuplicates = Arrays.asList(\"Mary\", \"Zheng\", \"Mary\", \"Zheng\");\n\t\tassertEquals(4, listHasDuplicates.size());\n\t\tHashSet<String> fromList = new HashSet<>(listHasDuplicates);\n\t\tassertEquals(2, fromList.size());\n\t}\n\n\t@Test\n\tpublic void via_stream() {\n\t\tHashSet<String> fromStream = Stream.of(\"Mary\", \"Zheng\").collect(Collectors.toCollection(HashSet::new));\n\t\tassertFalse(fromStream.isEmpty());\n\t\tassertTrue(fromStream.contains(\"Mary\"));\n\t\tassertTrue(fromStream.contains(\"Zheng\"));\n\t}\n\n\t@Test\n\tpublic void via_via_anonymous_collection() {\n\t\t@SuppressWarnings(\"serial\")\n\t\tHashSet<String> fromAnonymousClass = new HashSet<>() {\n\t\t\t{\n\t\t\t\tadd(\"Mary\");\n\t\t\t\tadd(\"Zheng\");\n\t\t\t}\n\t\t};\n\n\t\tassertFalse(fromAnonymousClass.isEmpty());\n\t\tassertTrue(fromAnonymousClass.contains(\"Mary\"));\n\t\tassertTrue(fromAnonymousClass.contains(\"Zheng\"));\n\t}\n\n}\n\n\n\n\nOutput\n\n\n\n\nRunning jcg.zheng.demo.HashSet_ConstructorTest\nTests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\n\n\n4.2 HashSet Common Methods\n\n\n\nThere are several common methods in HashSet:\n\n\n\nboolean isEmpty() - Returns true if this set contains no elements. Iterator<E> iterator() - Returns an iterator over the elements in this set.boolean add(E e) - Adds the specified element to this set if it is not already present. It has O(1) complexity.boolean remove(Object o) - Removes the specified element from this set if it is present. It has O(1) complexity. boolean contains(Object o) - Returns true if this set contains the specified element. It has O(1) complexity. int size() - Returns the number of elements in this set. It has O(1) complexity. \n\n\n\nHashSet is not thread safe because it throws ConcurrentModificationException if multiple threads access a HashSet object concurrently, and at least one of the threads modifies the set. In this step, I will create test methods to demonstrate.\n\n\n\nnot_thread_safe_cannot_modify_while_iterate() - Iterate and modify a HashSet object by calling the remove() method will throw ConcurrentModificationExceptionuse_iterator_remove - it's ok to remove the element via iterator.\n\n\n\nHashSetTest.java \n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport org.junit.Test;\n\npublic class HashSetTest {\n\n\tprivate Set<String> testClass = new HashSet<>();\n\n\t@Test\n\tpublic void can_add_null() {\n\t\tassertTrue(testClass.isEmpty());\n\t\ttestClass.add(null);\n\t\tassertFalse(testClass.isEmpty());\n\t\t\n\t\tboolean removed = testClass.remove(null);\n\t\tassertTrue(removed);\n\t\tassertTrue(testClass.isEmpty());\n\t}\n\n\t@Test\n\tpublic void can_read_while_iterate() {\n\t\ttestClass.add(\"Mary\");\n\t\ttestClass.add(\"Zheng\");\n\n\t\tIterator<String> iterator = testClass.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tString item = iterator.next();\n\t\t\tSystem.out.println(item);\n\t\t\tIterator<String> iterator2 = testClass.iterator();\n\t\t\twhile (iterator2.hasNext()) {\n\t\t\t\tSystem.out.println(\"\\titerator2 \" + iterator2.next());\n\t\t\t}\n\t\t}\n\t\ttestClass.clear();\n\t\tassertTrue(testClass.isEmpty());\n\t}\n\n\t@Test\n\tpublic void no_duplicate() {\n\t\tassertTrue(testClass.isEmpty());\n\t\t\n\t\tboolean added = testClass.add(null);\n\t\tassertTrue(added);\n\t\tassertFalse(testClass.isEmpty());\n\t\n\t\t\n\t\tadded = testClass.add(\"Mary\");\n\t\tassertTrue(added);\n\t\tassertEquals(2, testClass.size());\n\t\t\n\t\t\n\t\tadded = testClass.add(null);\n\t\tassertFalse(added);\n\t\t\n\t\tadded = testClass.add(\"Mary\");\n\t\tassertFalse(added);\n\t\t\n\t\n\t\t\n\t\tboolean removed = testClass.remove(\"Mary\");\n\t\tassertTrue(removed);\n\t\tassertEquals(1, testClass.size());\n\t\t\n\t\tremoved = testClass.remove(\"Mary\");\n\t\tassertFalse(removed);\n\t}\n\n\t@Test(expected = java.util.ConcurrentModificationException.class)\n\tpublic void not_thread_safe_cannot_modify_while_iterate() {\n\t\ttestClass.add(\"Mary\");\n\t\ttestClass.add(\"Zheng\");\n\n\t\tIterator<String> iterator = testClass.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tString item = iterator.next();\n\t\t\tif (\"Zheng\".equalsIgnoreCase(item)) {\n\t\t\t\ttestClass.remove(item);\/\/ will throw exception\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\t@Test\n\tpublic void order_is_not_same_as_inserted() {\n\t\tfor (int i = 0; i < 19; i++) {\n\t\t\ttestClass.add(String.valueOf(i));\n\t\t}\n\t\t\/\/ [11, 12, 13, 14, 15, 16, 17, 18, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\t\tSystem.out.println(testClass.toString());\n\t}\n\n\t@Test\n\tpublic void use_iterator_remove() {\n\t\ttestClass.add(\"Mary\");\n\t\ttestClass.add(\"Zheng\");\n\n\t\tIterator<String> iterator = testClass.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\tString item = iterator.next();\n\t\t\tif (\"Zheng\".equalsIgnoreCase(item)) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\n\t\tassertEquals(1, testClass.size());\n\t\tassertTrue(testClass.contains(\"Mary\"));\n\t\tassertFalse(testClass.contains(\"Zheng\"));\n\t}\n}\n\n\n\n\nOutput\n\n\n\n\nRunning jcg.zheng.demo.HashSetTest\n[11, 12, 13, 14, 15, 16, 17, 18, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nZheng\n iterator2 Zheng\n iterator2 Mary\nMary\n iterator2 Zheng\n iterator2 Mary\nTests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.195 sec\n\n\n\n4.3 Compare to TreeSet\n\n\n\nThe TreeSet class extends from AbstractSet and the elements are ordered based on their natural ordering. TreeSet has unique element like HashSet. But TreeSet cannot have the null element.\n\n\n\nIn this step, I will use test methods to compare HashSet to TreeSet.\n\n\n\nCompareToTreeSetTest.java \n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.ConcurrentModificationException;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\nimport java.util.TreeSet;\n\nimport org.junit.Test;\n\npublic class CompareToTreeSetTest {\n\n\tprivate String[] listHasDuplicates = { \"Shan\", \"Mary\", \"Mary\", \"Zheng\", \"Zheng\" };\n\tprivate Set<String> treeSet = new TreeSet<>();\n\n\t@Test\n\tpublic void HashSet_is_not_sorted_can_have_null() {\n\t\tlistHasDuplicates[listHasDuplicates.length - 1] = null;\n\t\tassertEquals(5, listHasDuplicates.length);\n\t\tSet<String> notOrderHashset = new HashSet<>(Arrays.asList(listHasDuplicates));\n\n\t\tSystem.out.println(notOrderHashset);\n\t\tassertEquals(4, notOrderHashset.size());\n\t}\n\n\t@Test(expected=ConcurrentModificationException.class)\n\tpublic void not_thread_safe_because_cannot_modify_while_iterate() {\n\t\ttreeSet.add(\"Mary\");\n\t\ttreeSet.add(\"Zheng\");\n\t\ttreeSet.add(\"Tom\");\n\t \n\t\tIterator<String> iterator = treeSet.iterator();\n\t\twhile (iterator.hasNext()) {\n\t\t\titerator.next();\n\t\t\ttreeSet.add(\"Test\");\n\t\t}\n\t\t \n\t}\n\n\t@Test(expected = NullPointerException.class)\n\tpublic void TreeSet_can_not_have_null() {\n\t\ttreeSet.add(null);\n\t}\n\t\n\t@Test\n\tpublic void TreeSet_is_sorted() {\n\t\tassertEquals(5, listHasDuplicates.length);\n\t\tTreeSet<String> orderedTreeSet = new TreeSet<>(Arrays.asList(listHasDuplicates));\n\n\t\tSystem.out.println(orderedTreeSet);\n\t\tassertEquals(3, orderedTreeSet.size());\n\t\tassertEquals(\"Mary\", orderedTreeSet.first());\n\t\tassertEquals(\"Zheng\", orderedTreeSet.last());\n\t}\n\n}\n\n\n\n\nOutput\n\n\n\n\nRunning jcg.zheng.demo.CompareToTreeSetTest\n[Mary, Shan, Zheng]\n[null, Shan, Zheng, Mary]\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.117 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n\n\n\n4.4 Compare to LinkedHashSet\n\n\n\nThe LinkedHashSet class extends from HashSet. The only difference between them is that LinkedHashSet maintains the insertion order. In this step, I will create test methods to compare HashSet to LinkedHashSet.\n\n\n\nCompareToLinkedHashSetTest.java \n\n\n\npackage jcg.zheng.demo;\n\nimport static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.LinkedHashSet;\n\nimport org.junit.Test;\n\npublic class CompareToLinkedHashSetTest {\n\n\tprivate String[] listHasDuplicates = { \"Shan\", \"Mary\", \"Mary\", \"Zheng\", \"Zheng\" };\n\tprivate LinkedHashSet<String> setObj;\n\n\t@Test\n\tpublic void is_not_sorted_can_have_null() {\n\t\tassertEquals(5, listHasDuplicates.length);\n\t\tlistHasDuplicates[listHasDuplicates.length - 1] = null;\n\t\tassertEquals(5, listHasDuplicates.length);\n\n\t\tsetObj = new LinkedHashSet<>(Arrays.asList(listHasDuplicates));\n\n\t\tSystem.out.println(setObj);\n\t\tassertEquals(4, setObj.size());\n\t}\n\n\t@Test\n\tpublic void LinkedHasSet_keeps_insertion_order() {\n\t\tassertEquals(5, listHasDuplicates.length);\n\t\tsetObj = new LinkedHashSet<>(Arrays.asList(listHasDuplicates));\n\n\t\tassertEquals(3, setObj.size());\n\t\t\/\/always \"Shan\", \"Mary\", \"Zheng\" order\n\t\tSystem.out.println(setObj);\n\n\t}\n\n}\n\n\n\n\nOutput\n\n\n\n\nRunning jcg.zheng.demo.CompareToLinkedHashSetTest\n[Shan, Mary, Zheng]\n[Shan, Mary, Zheng, null]\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.135 sec\n\n\n\n5. Summary\n\n\n\nIn this example, I demonstrated several ways to create a HashSet object and how to use its common methods. I also compared HashSet to TreeSet and LinkedHashSet.\n\n\n\nHashSetLinkedHashSetTreeSetUnique ElementsYesYesYesPermit Null ElementYesYesNoMaintain Insertion OrderNoYesNoIs SortedNoNoYesIs thread-safeNoNoNo\n\n\n\n6. More articles\n\n\n\nJava Set ExampleHashmap Java Example\n\n\n\n7. Download the Source Code\n\n\n\nThis example consists of a Maven project which contains several Junit tests to demonstrate the usage of the HashSet Class.\n\n\n\nDownload\nYou can download the full source code of this example here: Hashset Java Example\n\n\n\nLast updated on Apr. 23rd, 2021\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/hashset-java-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Mary Zheng","url":"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2020-02-14T09:00:00+00:00 |
| article:modified_time | 2022-07-06T10:26:20+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Mary Zheng |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Mary Zheng |
| twitter:label2 | Est. reading time |
| twitter:data2 | 7 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1