RubenVerhaegh
RubenVerhaegh

Reputation: 13

An HashMap (or ArrayList) that contains different Fragments

For a certain situation, I want to make a HashMap where the keys are Fragments and the values are Integers. However, every different Fragment has a different type and is not simply of the type Fragment. So the following (which is what I initially tried) doesn't work:

HashMap<Fragment, Integer> hmap = new HashMap<>();
hmap.put(new ExampleFragment(), 5);
hmap.put(new AnotherFragment(), 2);

Now this won't work of course, since ExampleFragment and AnotherFragment are not of the correct type to be put in the HashMap.
EDIT: I get the following error in AndroidStudio: Wrong 1st argument type. Found: 'com.example.sword.rpg.ExampleFragment', required: 'android.app.Fragment'

Now my question is: how do I store different SubClasses of Fragment in the same HashMap (or ArrayList for that matter) and is this even possible?

I do have a workaround for my specific situation, but it is not as neat as this one would have been. So I'm still curious.

EDIT: I indeed mixed up Fragment and android.support.v4.app.Fragment, thanks :)

Upvotes: 0

Views: 219

Answers (1)

user2711811
user2711811

Reputation:

To your question, it should work, as this does, so is it possible you mixed up your "fragment" types? There's a few in typical android namespace (e.g. android.app.Fragment vs android.support.v4.app.Fragment):

import android.app.Fragment;
import android.util.Log;
import java.util.HashMap;

public class TestHashMap {

      private HashMap<Fragment, Integer> test = new HashMap<>();

      public static class ExampleFragment extends Fragment {
          public ExampleFragment() { super(); }
          public String toString() { return "ExampleFragment[hash:"+hashCode()+"]"; }
          public void someOtherMethod() {}
      }

      public static class AnotherFragment extends Fragment {
          public AnotherFragment() { super(); }
          public String toString() { return "AnotherFragment[hash:"+hashCode()+"]"; }
      }

      public void test() {
          test.put(new ExampleFragment(),1);
          test.put(new AnotherFragment(),2);
          Log.d("TestHashMap","size = "+test.size());
          Log.d("TestHashMap",test.toString());
      }
  }

Which produces:

D/TestHashMap: size = 2
D/TestHashMap: {AnotherFragment[hash:230309272]=2, ExampleFragment[hash:5536635]=1}

Upvotes: 1

Related Questions