getter setter for Hashmap using generics

I have the following two classes

Animal Class

class Animal {

  Map<String, A> data = new HashMap <String, A>();

  public void setValue(HashMap<String, ?> val)
   {
     this.data = val;
   }
  public Map getValue()
   {
    return this.data;
   }
}

Dog Class

class Dog extends Animal {

  public void index()
  { 
    Map<String, A> map = new HashMap<String, A>();

    map.put("name", "Tommy");
    map.put("favfood", "milk"); // want to pass Lists, Integers also
    setValue(map);
  }
}

As you can see from the above code I am trying to set some values with keys in index method, but I am getting error warnings from eclipse in both two files. Error Messages are:

In Dog Class File:

Multiple markers at this line
    - A cannot be resolved 
     to a type
    - A cannot be resolved 
     to a type

In Animal Class File :

Multiple markers at this line
    - A cannot be resolved to a type
    - A cannot be resolved to a type
    - Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments 
     <HashMap<String,A>>

The data type of the keys in HashMap will always be a String but the data types of values would be random, hence I am trying to use Generics.

Coming from PHP background I still haven’t been able to grasp the concept of Java Generics. Could you please tell me where is the mistake in my code?

Answer

While this kind of setup is not the ideal way to go, one solution is to make your Map a <String, Object> generic type. In this way you can put whatever you want into the Object part. This will, however, be a pain to pull that information back out. This is how I see your classes changing.

class Animal {

      Map<String, Object> data = new HashMap <String, Object>();

      public void setValue(Map<String, Object> map)
       {
         this.data = map;
       }
      public Map<String, Object> getValue()
       {
        return this.data;
       }
    }

class Dog extends Animal {

      public void index()
      { 
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("name", "Tommy");
        map.put("favfood", "milk"); // want to pass Lists, Integers also
        setValue(map);
      }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *