• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Re-inserting data into Set?

 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is that possible?? Here is excerpt from LinkedHashSet javadoc:


This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)



javadoc for add(Object):


Adds the specified element to this set if it is not already present.

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Vladas,

The question of yours is very interesting. From the most emminent
point of view: It should not matter if the element is re-inserted
or if the add is just ignored when adding the same element. Sets
generally work on an equality basis, which means that if you are
inserting an element

the result is that the set will not contain 2 elements for which

For example if you work with Strings, you cannot have 2 equal strings
in the Set. You can call "add" multiple times on the same object:

but there will be only one "Hello" in the set. In this case it does
not really matter whether the set contains the first "Hello" or the third
"Hello" because it is always the same "Hello". Technicaly you can do it
and your semantics should be such, that it makes no difference.

But now let us have a look at an example of bad programming:

It is not so easy anymore:

You know what I mean? Well, to wrap it up, I would rather believe
the documentation in Set, which says, that a re-insertion is ignored.
It also makes sense from the performance point of view.
On the other hand you should think of a Set as of an abstraction of
the mathematical set. Therefore it should not matter and your code
should not depend on it. (And as for the "BAD" code above, it would
be better to do:

I hope it helped.
Petr
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic