0

If I have code that looks like this:

Collection<Object> c = new HashSet<Object>();

will it still retain the properties that the collection will not be able to contain duplicate values. In other words, what would happen in the following situation?

String h = "Hello World!";
c.add(h);
c.add(h);
4

5 回答 5

2

Yes, the behavior and properties of Set will still hold. c will only contain one instance of "Hello World!"

public static void main(String[] args)
{
    Collection<Object> c = new HashSet<Object>();
    String h = "Hello World!";
    c.add(h);
    c.add(h);
    System.out.println("c contains " + c.size() + " item(s): " + c);
    System.out.println("c is an instance of " + c.getClass());
}

The above main method outputs:

c contains 1 item(s): [Hello World!]
c is an instance of class java.util.HashSet
于 2012-06-01T00:17:15.493 回答
2

You're not "constructing a Collection"; you're merely create a new reference. So yes, all the underlying properties still hold, because it's still the original object's methods that you're calling.

于 2012-06-01T00:17:55.913 回答
1

Short: yes - it is still an object of HashSet even if the referencing variable type is a super type of HashSet.

于 2012-06-01T00:18:13.723 回答
1
HashSet<T> theSet = new HashSet<T>();
Collection<T> collection = theSet;
Iterable<T> iterable = theSet;
Object object = theSet;

All of these four variables are of different types (all of them have to be super types of HashSet by the way), but all of them refer to the same object whose type is HashSet. No matter what variable you use to access the object, it will always behave in the same way. This is one of the key features of polymorphism.

The only difference is that the higher you move the inheritance tree (up means towards more general types), the less methods and fields are accessible for you. So you cannot call methods such as object.iterator(), iterable.size() etc., but when you call a method common for all the variables, it always behaves the same way:

theSet.toString(); // produces []
collection.toString();  // produces []
iterable.toString()  // produces []
object.toString(); // produces []
于 2012-06-01T00:28:51.300 回答
0
String h = "Hello World!";
c.add(h);//Returns true
c.add(h);//Returns false since duplicate elements are not allowed in HashSet

So only one instance of h will be added to HashSet
于 2012-06-01T00:22:59.130 回答