简体   繁体   中英

questions on using hashset to define a new set

With respect to the following two different definitions of sets, what are the differences:

Set<Integer> intset = new Hashset<Integer>();

Set<Integer> intset = new Set<Integer>();

Thanks.

Since Set is an interface, the second won't compile.

You can't declare new Set its an interface. All of those(Set, Map, List) are interfaces the java.collections package. They are not directly instantiable, but require that implementations(HashSet, ArrayList, Hashmap) be supplied in the right hand side of the assignment operation.

The second one won't even compile. Often people ask what's the difference between these :

HashSet<Integer> intset = new Hashset<Integer>();

Set<Integer> intset = new HashSet<Integer>();

and perhaps that's what you meant to ask. The difference here is that code written using the first definition is dependent on the particular choice of Set implementation (HashSet vs. TreeSet or something else) whereas the second declaration would let you trivially change to a different implementation without modifying any other code. It's a good practice in general -- keeps you flexible.

java.util.Set is an interface while java.util.HashSet is an actual implementation.

You cannot instantiate a Set the way you are in your second definition.

Set is an Interface, and cannot be instantiated, it simply defines a contract by which concrete implementations can follow.

You can, however, instantiate an anonymous inner class that would follow Set's interface:

Set<Integer> intSet = new Set<Integer>() {
    //need to define all set methods here...
};

In JavaSet is an interface and thus cannot be initiated, thus the second one is wrong.

But the actual difference in terminology is that a Set is a mathematical concept conveying to some rules (eg uniqueness, order non-importance). A HashSet is a technique to implement the Set concept, using a Hashtable , which makes it computationally very fast --- amortized constant time insertion, deletion and access.

Set is an interface that provides some abstract methods for specific Set implementations to provide. You can't initialize a Set object, the same way you can't a List . An interface is similar to a class, however everything it contains is abstract and a class can implement multiple interfaces, but only extend a single class. Also, a class can contain both abstract and concrete methods while an interface can't. Interfaces are sort of a way of dealing with multiple inheritance.

Anyway: http://download.oracle.com/javase/6/docs/api/java/util/Set.html http://download.oracle.com/javase/tutorial/java/concepts/interface.html

Compiler error on line:

Set<Integer> intset = new Set<Integer>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM