0

Gives "non-static variable this cannot be referenced from a static context"

This is the code below for template class

public class BiHashMap<K1, K2, V>{

    private final Map<K1, Map<K2, V>> mMap;

    public BiHashMap() {
        mMap = new HashMap<K1, Map<K2, V>>();
    }

    public V put(K1 key1, K2 key2, V value) {
        Map<K2, V> map;
        if (mMap.containsKey(key1)) {
            map = mMap.get(key1);
        } else {
            map = new HashMap<K2, V>();
            mMap.put(key1, map);
        }

        return map.put(key2, value);
    }

}

public static void main(String[] args) {
    BiHashMap<double,double,double> table1 = new BiHashMap<double,double,double>();
    table1.put(0.375,1,350);

I tried making a new class for double but the error remained

public class dbble{
    double number;

    dbble(double x){
        number=x;
    }
}
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
  • What is the error log? – TuyenNTA Apr 30 '17 at 22:48
  • 1
    You can't use **primitive types** as template parameters (Java doesn't have template parameters, you mean generic types), you must use the wrapper types. – Elliott Frisch Apr 30 '17 at 22:48
  • @ElliottFrisch are right. Just change `new BiHashMap();` to `new BiHashMap();` – TuyenNTA Apr 30 '17 at 22:51
  • Change your `put` function to static, because you can not call a non static function inside a static function. – TuyenNTA Apr 30 '17 at 22:54
  • @TuyenNguyen Tried doing this but got this new error 'Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: ' – Ali Ariz Apr 30 '17 at 23:00

1 Answers1

0

I have test your code above and edit it to make it run: (You have to put the main function inside the class, you need to use wrapper type for double, and cast the value you put to when you call the function).

public class BiHashMap<K1, K2, V> {

private final Map<K1, Map<K2, V>> mMap;

public BiHashMap() {
    mMap = new HashMap<K1, Map<K2, V>>();
}

public V put(K1 key1, K2 key2, V value) {
    Map<K2, V> map;
    if (mMap.containsKey(key1)) {
        map = mMap.get(key1);
    } else {
        map = new HashMap<K2, V>();
        mMap.put(key1, map);
    }

    return map.put(key2, value);
}

public static void main(String[] args) {
    BiHashMap<Double, Double, Double> table1 = new BiHashMap<Double, Double, Double>();
    table1.put(0.375, Double.valueOf(1), Double.valueOf(350));
}
}
TuyenNTA
  • 1,194
  • 1
  • 11
  • 19