Orion
Orion

Reputation: 59

How to add element at specific index/position in HashSet?

I have some HashSet collection of String elements, how I can add new element at specific position? I saw documentation and didn't find any method that can do it.

Upvotes: 2

Views: 11173

Answers (2)

vx apollo
vx apollo

Reputation: 1

we can see pic use list to add at particular index and then add that list to set using object.addAll(listobject or setobject

Set<Integer> s=new HashSet<Integer>();
Set<Integer> s1=new HashSet<Integer>(); 
s1.add(6);
List<Integer> l=new ArrayList<Integer>();
l.add(5);
l.add(2,2);
l.add(0);
System.out.println(l);
S.addAll(l);//list
S.addAll(s1);//another set

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

One of the aspects of a standard HashSet<T> is that it is unordered. So you cannot insert an element at a specific index. Or as is specified in the documentation:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

When you do an insertion, deletion, etc. it is possible that the HashSet<T> will do a rehashing. As a result the order of the elements in a for(...) loop can change completely.

There exists an extension of a Hashset<T>, the LinkedHashSet<T> which maintains the order of the elements in which they were inserted.

A TreeSet<T> on the other hand, uses a tree, and orders the elements according to an order relation (an object that is less than another object, is emitted before that element).

It would be weird if you could insert an element at a random index, since that would result in O(n) time for at least some operations with a specific index. Usually one uses a HashSet<T> to perform insertions, removal, etc. in O(1) (average time).

Upvotes: 7

Related Questions