0

everyone!

Just started studying Java and can not understand one moment, for example:

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

HashSet<Integer> intset2 = new HashSet<Integer>(); (2)

What is the difference between these examples? Or they are the same? (1) example looks like up-casting, so it means that we have HashSet with only Set(interface) methods? Thank you for your reply!

JavaBeigner
  • 608
  • 9
  • 28
BillyJoe
  • 11
  • 2
  • I'm not sure about the duplication... There is the question "What is the difference" and the question "Why to prefer using the interface". They are two distinct questions and besides the fact the talk about the same topic, they don't even overlap each other. – Desorder Sep 15 '14 at 21:45

4 Answers4

4

When you write

Set intset = new HashSet();

You give the guarantee that the following code, if not casting, won't use any of the specificities of the HashSet class. This means future implementations may replace HashSet with any other implementation of Set, or maybe receive it from elsewhere. This is actually a best practice as it means your code is less coupled.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Set is an interface and HashSet is an hash implementation of Set interface.

The inset is a Set, so, it can refer any implementation of a Set, like HashSet. On other hand, inset2 can only refer an HashSet object.

Rustam
  • 6,485
  • 1
  • 25
  • 25
Cold
  • 787
  • 8
  • 23
1

This is polymorphism.

What is the difference between these examples?

Example one creates a "pointer" to the space in memory of a type of a Set. That means that you will have ability to manipulate that space in memory using all methods declared in the Set interface.

Example two creates a "pointer" to the space in memory of a type of a HashSet. That means that you will have ability to manipulate that space in memory using all methods declared in the HashSet class.

Or they are the same?

It depends on what you are going to do after those two lines. Set is a common contract for the Set-like collections but sometimes we need more specific methods. That is when you need to downcast you Object to a more specific type. Interfaces are supposed to deal with the commonality.

(1) example looks like upcasting, so it means that we have HashSet with only Set(interface) methods?

Yes.

Desorder
  • 1,549
  • 12
  • 16
0

Set[Set][1] is an interface, HashSet[HashSet][2] is a class, Implementing Set interface methods in HashSet classes, HashSet class implements Set interface