尝试制作一个自定义的HashMap类,但我坚持使用GetEnumerator。
当我将鼠标悬停在&test; test.entrySet()'这显示
' foreach语句不能对类型' Project.Map'的变量进行操作。不包含' GetEnumerator''
的公开定义我的foreach循环看起来像这样
foreach(Map<string, object> e in test.entrySet()) {
}
我的HashMap类看起来像这样
public class HashMap<K, V> {
private List<object> k = new List<object>();
private List<object> v = new List<object>();
public void put(object k, object v) {
this.k.Add(k);
this.v.Add(v);
}
public object get(object k) {
var i = 0;
foreach (var key in this.k) {
if (k.Equals(key)) {
return this.v.ElementAt(i);
}
i++;
}
return null;
}
public bool exist(object k) {
return this.k.Contains(k);
}
public void clear() {
this.k.Clear();
this.v.Clear();
}
public Map entrySet() {
return null;
}
}
我的Map类看起来像。我觉得这堂课没用......
public class Map<K,V> {
private List<object> k = new List<object>();
private List<object> v = new List<object>();
public Map(List<object> k, List<object> v) {
this.k = k;
this.v = v;
}
public object getKey() {
return null;
}
public object getValue() {
return null;
}
}
如果有人可以帮我修复此代码/提供一些提示,我会非常高兴。
应该看起来像这样的事情
HashMap<string, object test = new HashMap<string, object>();
foreach(Map<string, object> e in test.entrySet()) {
string key = e.getKey();
string value = e.getValue();
}
答案 0 :(得分:0)
我认为您不希望getValues()
方法返回Map
。如果您想获取HashMap
中的值,则只需返回v
对象。
public List<object> getValues() {
return v.AsReadOnly();
}
另外请注意,您的HashMap
类有通用变量,但在任何地方都没有使用过。您希望将object
替换为通用类型。
即
private List<K> k = new List<K>();
private List<V> v = new List<V>();
并更改您的功能
即
public V get(K k) {