-7

I am using LinkedHashSet for storing elements. Here is the sample code

Set<String> s = new LinkedHashSet<String> ();
s.add("B");
s.add("C");
s.add("F");

May I know if the order is going to be preserved as my reference is of type Set but object is of type LinkedHashSet?

vk83
  • 1
  • 3
    Read : https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html – Suresh Atta Jun 27 '17 at 16:50
  • 2
    Read the docs. It's literally the first sentence. https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html – Kon Jun 27 '17 at 16:50
  • 4
    It's probably polymorphism you need to look into. – Sotirios Delimanolis Jun 27 '17 at 16:50
  • 2
    Possible duplicate of [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – OH GOD SPIDERS Jun 27 '17 at 16:54
  • @OHGODSPIDERS it is not even close to be duplicate – luizfzs Jun 27 '17 at 16:56
  • @luizfzs If one reads and understands the "program to interface" question and answers then it answers this question as well as it explains the principle behind what "Interface x = new ConcreteClass" actually means. – OH GOD SPIDERS Jun 27 '17 at 17:02
  • @OHGODSPIDERS, the hereby question is related to order-preservation on the data structure, not related to inheritance. This question does note refer to inheritance neither to interface. – luizfzs Jun 27 '17 at 17:06
  • 1
    @luizfzs No. The asker knows that LinkedHashSet preserves the order but wants to know if having his variable as reference type Set changes that. Set is an Interface and LinkedHashSet a concrete implementation of that interface. The conrete implementation handles the logic as described in the question i linked. So that actually answers the question. – OH GOD SPIDERS Jun 27 '17 at 17:10
  • @OHGODSPIDERS. Sorry, my bad :( You are right. I misread the question. – luizfzs Jun 27 '17 at 17:13

1 Answers1

0

According to Java documentation, since LinkedHashSet, is a implementation of Set the order will be according to insertion, so in your example it will be like {"B", "C", "F"}.