Reputation: 65
How do I get the index of element in HashSet when using java?
Let's say
HashSet<Character> hs = new HashSet<Character>();
hs.add('s');
hs.add('t');
hs.add('a');
hs.add('c');
// some code
if (hs.contains('a')) {
int a = // need the index of a here from hashset
}
The runtime for lookup has to be linear with any data structure.
Upvotes: 0
Views: 9260
Reputation: 706
HashSet
Class hasn't any functions to find the index of something inside it, So you can use something like ArrayList
or List
, But if you want to use HashSet
any way, Then only way to find the item's index is by iterating it like:-
HashSet<Character> hs = new HashSet<Character();
hs.add('s');
hs.add('t');
hs.add('a');
hs.add('c');
int foundIndex = -1;
for(int i=0; i<hs.size(); i++){
if(hs.get(i).equals('a')){
foundIndex = i;
break;
}
}
if(foundIndex == -1){
//The value wasn't in the HashSet
}else{
int a = foundIndex;
//The value was found
}
Upvotes: 0
Reputation: 614
A Set in unordered, so you cannot get an index from it. If you still want to get index from a set, you can opt for iterating through it.
HashSet<Character> hs = new HashSet<Character>();
Iterator it = hs.iterator();
int index =-1;
while(it.hasNext()){
i++;
if(value.next()=='a'){
return;
}
}
return i== (hs.size()-1) ? -1 : i;
Constant time lookup will be traded off in this way because of unorderedness of HashSet.
Upvotes: 0
Reputation: 448
The set does not have the index by definition. Instead, try to use something like HashMap. This would give you constant time for containsKey:
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
hm.put('s',1);
hm.put('t',2);
hm.put('a',3);
hm.put('c',4);
// some code
if (hm.containsKey('a')){
int a = hm.get('a') //index is here
}
Upvotes: 0
Reputation: 2375
The Set interface doesn't have something like as an indexOf()
method. You'd really need to iterate over it or to use the List interface instead which offers an indexOf()
method.
If you would like to, converting Set to List is pretty simple, it should be a matter of passing the Set through the constructor of the List implementation. E.g.
List<String> nameList = new ArrayList<String>(nameSet);
Upvotes: 3