-1

Tried to make a custom HashMap class but im stuck with GetEnumerator.

When i hover over 'test.entrySet()' this shows up

'foreach statement cannot operate on variables of type 'Project.Map' does not contain a public definition for 'GetEnumerator''

My foreach loop looks like this

foreach(Map<string, object> e in test.entrySet()) {

}

My HashMap class looks like this

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;
    }
}

My Map class looks like. I think this class is useless...

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;
    }
}

If someone could help me fix this code/give some tips i would be verry glad.

Should look somthing like this

HashMap<string, object test = new HashMap<string, object>();

foreach(Map<string, object> e in test.entrySet()) {
    string key = e.getKey();
    string value = e.getValue();
} 
8803286
  • 81
  • 2
  • 10
  • Why are you creating a custom HashMap? Can you make `test` a [Dictionary](https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx)? Or is the goal to create a custom HashMap? – edkek Oct 06 '17 at 22:34
  • I cant use Dictionary like a HashMap thats why i make a custom one – 8803286 Oct 06 '17 at 22:45

1 Answers1

0

I don't think you want your getValues() method to return a Map. If you want to get the values in the HashMap, then just return the v object.

public List<object> getValues() {
    return v.AsReadOnly();
}

Also a side note, your HashMap class has generic variables but their not used anywhere. You want to replace object with whatever the generic type is.

i.e

private List<K> k = new List<K>();
private List<V> v = new List<V>();

and change your functions

i.e.

public V get(K k) {
edkek
  • 221
  • 1
  • 10