Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Wednesday, 24 July 2013

Latest HashSet Interview Question Related to Concept of working of HashSet

HashSet in Java is a collection which implements Set interface and backed by an HashMap. Since HashSet uses HashMap internally it provides constant time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order. Iterator of HashSet is fail-fast and throws ConcurrentModificationException if HashSet instance is modified concurrently during iteration by using any method other than remove() method of iterator class.If you want to keep insertion order by using HashSet than consider using LinkedHashSet. It is also a very important part of any Java collection interview, In short correct understanding of HashSet is must for any Java developer.




Java HashSet Examples TutorialsIn this Java tutorial we will learn various examples of HashSet in Java and how to perform different operations in HashSet with simple examples. There is also a very famous interview questions based on HashSet is difference between HashMap and HashSet in java, which we have discussed in earlier post. You can also look that to learn more about HashSet in Java.


How to create HashSet object in Java
Creating HashSet is not different than any other Collection class. HashSet provides multiple constructor which gives you flexibility to create HashSet either copying objects from another collection, an standard way to convert ArrayList to HashSet. You can also specify initialCapacity and load factor to prevent unnecessary resizing of HashSet.


HashSet assetSet = new HashSet(); //HashSet instance without any element
HashSet fromArrayList = new HashSet(Arrays.asList(“Java”,”C++”)); //copying content
HashSet properSet = new HashSet(50); //HashSet with initial capacity




How to store Object into HashSet
Storing object into HashSet, also called elements is similar to Other implementation of Set, add() method of Set interface is used to store object into HashSet. Since Set doesn’t allow duplicates if HashSet already contains that object, it will not change the HashSet and add() will return false in that case.


assetSet.add("I am first object in HashSet"); // add will return true
assetSet.add("I am first object in HashSet"); // add will return false as Set already has




How to check HashSet is empty
There are multiple ways to check if HashSet is empty. An HashSet is called empty if it does not contain any element or if its size is zero. You can get size of HashSet as shown in further example and than see if its zero or not. Another way to do is by using isEmpty() method which returns true if underlying Collection or HashSet is empty.


boolean isEmpty = assetSet.isEmpty(); //isEmpty() will return true if HashSet is empty


if(assetSet.size() == 0){
    System.out.println("HashSet is empty, does not contain any element");
}

How to remove objects from HashSet in Java
HashSet in Java has nice little utility method called remove() remove object from HashSet. remove() deletes the specified object or element from this Set and returns true if Set contains element or false if Set does not contain that element. You can also use Iterator’s remove method for deleting object while Iterating over it.


assetSet.remove("I am first object in HashSet"); // remove will return true
assetSet.remove("I am first object in HashSet"); // remove will return false now


Iterator setIterator = assetSet.iterator()
while(setIterator.hasNext()){
   String item = setIterator().next();
   setIterator.remove(); //removes current element
}




How to clear HashSet in Java
HashSet in Java has a clear() method which removes all elements from HashSet and by clearing HashSet you can reuse It, only problem is that during multi-threading you need to be extra careful because while one thread is clearing objects form HashSet other thread can iterate over it.


assetSet.clear(); //clear Set, size of Set will be zero now


How to find size of HashSet in java
Size of HashSet returns number of objects stored in Collection. You can find size of HashSet by calling size() method of HashSet in Java. For an empty HashSet size() will return zero.


int size = assetSet.size(); // count of object stored in HashSet




How to check if HashSet contains an object
checking existence of an object inside HashSet in Java is not difficult, HashSet provides a utility method contains(Object o) for very same purpose. contains returns true if object exists in collection otherwise it returns false. By the way contains() method uses equals method to compare two object in HashSet. That’s why its important to override hashCode and equals method in Java.


assetSet.contains("Does this object exists in HashSet"); //contains() will return false
assetSet.add("Does this object exists in HashSet"); //add will return true as its new object
assetSet.contains("Does this object exists in HashSet"); // now contains will return true

How to convert HashSet into array in Java
HashSet has an utility method called toArray() inherited from Set interface. which is used to convert a HashSet into Array in Java see following example of converting hashset into array. toArray() returns an object array.


Object[] hashsetArray = assetSet.toArray();
Set<String> stringSet = new HashSet<String>();
String[] strArray = stringSet.toArray();


After Java 1.5 this method accept generics parameter and It can return the same type of element which is stored in HashSet. If size of Array is not sufficient than a new Array with runtime type of elements in HashSet is created. If you want to convert HashSet into Array List than search on Javarevisited.




That's all on this Java HashSet tutorial. HashSet in java is a one of the frequently used Collection class and can be very useful on certain scenario where you need to store unique elements with quick retrieval. important point to not about java HashSet it that add, remove, contains() and size() is constant time operation.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...