Type Definition for Java Collection

Is there a way to determine the type of collection?

If I have the following:

private Map<String, A> myMap;

that is, a way to define Map<String, A>as a new type MapOfTypeA, for example, so that I can define myMap as

private MapOfTypeA myMap;

as an extension of this, is there a way to have the following:

myMap = new MapOfTypeA();

really

myMap = new HashMap<String, A>();

I'm not sure what to call what I ask, but I think I explained it. I think in C or C ++ this will be a typedef.

+2
source share
6 answers

You can define MapOfTypeA as

class MapOfTypeA extends HashMap<String, A> {
}

But I don’t know what the goal is. If your concern is verbosity, then Java 7 introduced a diamond operator that you can use to declare your card as follows:

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

instead

Map<String, A> myMap = new HashMap<String, A> ();
+3
source

Something like that?

class MapOfTypeA extends HashMap<String, A> { }

:

private MapOfTypeA myMap;

- , , , . , , , , .; -)

+1

, ?

public class MapOfTypeA extends HashMap<String, A>{}

MapOfTypeA , HasMap.

... , (?)

+1

Java typedefs aliases. , , :

class MapOfA extends <String, A> {}
MapOfA aMap = new MapOfA();

, , ():

class MapFromString<X> extends Map<String, X> {}
+1

1) ,

public class StringKeyedMap<V> extends ConcurrentHashMap<String,V> {

  public static void main(String[] args) {
    StringKeyedMap<Integer> stringToIntegerMap = new StringKeyedMap<Integer>();
    stringToIntegerMap.put("some-key", Integer.valueOf(7));
  }
}

2) the key and value of the card are always the same type

public class MyMap extends ConcurrentHashMap<String,Integer> {

  public static void main(String[] args) {
    MyMap myMap = new MyMap();
    myMap.put("some-key", Integer.valueOf(7));
  }
}
+1
source

In the Java Terms, this is a Generics call: http://en.wikipedia.org/wiki/Generics_in_Java

And so, as you defined it, it is absolutely correct.

but you probably need to go back how you define your hash file.

If you want hashmap to have both A and MapOfTypeA, and MapOfTypeA is a subclass of A class MapOfTypeA extends A, then your hash must be specified this way.

HashMap<String, MapOfTypeA> myMap;
0
source

Source: https://habr.com/ru/post/1776571/


All Articles