Which is the Best Java Web Framework ?

Java - Collections - Interview Questions and Answers on HashSet

Q1. In What order does HashSet maintains its elements ?

Ans. HashSet doesn't maintain elements in fixed order.

Q2. How  to initialize HashSet ?

Ans. Set<String> mySet = new HashSet<String>(Arrays.asList("String element 1", "String Element 2"));

Q3. Can can I initialize HashSet using a List ?

Ans. Set<String> mySet = new HashSet<String>(<List Reference>);

Q4. What is the relation between HashCode and HashSet ?

Ans. Hashcode is used for bucketing in HashSet.

Q5.  What will be the output of this code ?

Set<String> mySet = new HashSet<String>();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
    System.out.println(s);
}

Ans. It will print 4567,5678 and 6789 but Order cannot be predicted.

Q6.  What will be the output of this code ?

Set<String> mySet = new HashSet<String>();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
System.out.println(s.get(0));

Ans. This will give compile time error as we cannot retrieve the element from a specified index using Set. Set doesn't maintain elements in any order. 

Q7.  What will be the output of the following code ?

enum Day {

 MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

public class BuggyBread1{

    public static void main (String args[]) {
     Set<Day> mySet = new HashSet<Day>();
     mySet.add(Day.SATURDAY);
     mySet.add(Day.WEDNESDAY);
     mySet.add(Day.FRIDAY);
     mySet.add(Day.WEDNESDAY);
     for(Day d: mySet){
      System.out.println(d);
     }
    }
}

Ans. FRIDAY, SATURDAY and WEDNESDAY will be printed but the order cannot be determined.

Only one FRIDAY will be printed as Set doesn't allow duplicates.

Order cannot be determined as HashSet doesn't maintain elements in any particular order.

Q8. Which is the Parent Class of HashSet class?

Ans.java.util.AbstractSet<E>

Q9. Which are the subclasses for HashSet?

Ans.[JobStateReasons, LinkedHashSet, ]

Q10. What is the package name for HashSet class?

Ans.java.util

Q11. Which interfaces are implemented by HashSet?


Ans.[, Serializable, Set<E>, Cloneable, Collection<E>, Iterable<E>]

Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.