我现在正在编写MapClass,但是我似乎不能理解put方法。这就是我到目前为止所知道的:
public V put(K key, V value)
{
for(MapEnt<K,V> x:data)
{
if(x.getKey().equals(key))
{
V reval = x.getValue();
x.setValue(value);
return reval;
}
else
{
}
}
return null;
}我在添加条目时遇到了问题。我有一个键和值的ArrayList。
非常感谢!
发布于 2015-10-25 08:54:46
Nothing (不删除任何部件)(即删除else部件)。您不想在那里做任何事情,以防稍后在列表中找到具有适当键的条目。
在循环之后,您需要添加一个新条目,因为您知道条目列表中没有具有适当关键字的条目。
顺便说一下:如果您希望允许密钥为null,请使用Objects.equals来检查相等性,而不是调用equals (这可能会产生NullPointerException)
发布于 2015-10-25 10:11:12
有更好的方法可以做到这一点(细节取决于您正在实现的映射的类型)。然而,这可能是您所要求的。
// Returns matching value or null if no value exists for this key.
public V put( K key, V value )
{
V existingValue = null;
// The downside of this for each loop is that it will iterate through all
// entries, even if a match is found part way through.
for ( MapEnt<K, V> x : data )
{
if ( x.getKey().equals( key ) )
{
// Match found.
existingValue = x.getValue();
x.setValue( value );
}
}
if ( existingValue == null )
{
// No match was found. add new entry (exactly where you add it will
// Depend on the type of map you are implementing.
}
return existingValue;
}https://stackoverflow.com/questions/33324956
复制相似问题