Re: HashMap problem: insert with hash code retrieve by index
Royan wrote:
Lets say we have the following class
public class Foo {
private Map<Integer, String> dataMap = new HashMap<Integer,
String>();
public String getValueAt(int idx) {
// I wish I don't use for loop here ...
}
This part is doable. You shouldn't include implementation in variable names.
public void addValue(String s) {
String l = dataMap.put(getHashCode(s), s);
}
}
This part will always have a finite risk of failure.
You have the right Map definition. Bear in mind that only *one* Integer of
any given value can key the Map, and so if two Strings have the same
hashCode(), you'll lose one of them. That said,
<untested_example>
public class Foo
{
private final Map <Integer, String> data =
new HashMap <Integer, String> ();
public String put( String val )
{
return data.put( val.hashCode(), val );
}
public String get( Integer key )
{
return data.get( key );
}
}
</untested_example>
As you can see, the class is a very thin cover for Map <Integer, String>.
--
Lew