Link to home
Start Free TrialLog in
Avatar of booksplus
booksplus

asked on

ArrayList versus HashMap

If I'm using an ArrayList as a cache to tell me if I looked something up and did not find anything - SO don't look it up again - THEN
I don't actually need the value - I ONLY need the key.

THEREFORE my question is - in this case what is faster a HashMap or an ArrayList.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

HashSet
Avatar of laes_
laes_

HashMap
u put the key it gives the value
Values are not needed, right?
if u want just the key exist or not =>
  public classname getobjectuwant(String key) {
    classname objectname =null;
    boolean found=false;
    for(Iterator i=hashmap.keySet().iterator();i.hasNext();){
      objectname =(classname)hashmap.get((String)i.next());
      if(objectname .getLabel().equals(label)) {
        found=true;
        break;
      }
    }
    return found?objectname :null;
  }
boolean present = hashSet.contains(x);

boolean present = hashMap.containsKey(x);
if(objectname .getLabel().equals(label)) {
replace with
if(objectname .getLabel().equals(key)) {
Avatar of booksplus

ASKER

CEHJ - to answer your question - YES,  values are not needed.
HashSet is the way to go then
ArrayList
if performance is your concern then use a TreeMap, or a TreeSet.
They'll provide the fastest lookup.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> In descending order of lookup:

I'd check your sources because that is incorrect.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>O(C) for hashset is only applicable is it is assumed that ...

That's all correct, but with care, you should be able to get pretty close to O(C)
seet82 -
what do you mean "the keys are distributed evenly"  - I want to better understand what you are saying.  And please  remind me about meaning
O(C), etc.

Thanks.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)