简体   繁体   中英

How can I create a map with chars as key values and arrays of strings as mapped values - arrays must be of different length?

I am unsure of the syntax required to make a map where key values are type char and mapped values are type string array. The arrays need to be different lengths. Something like:

map <char, string> backtranslate;
backtranslate['M'] = {"ATG"};
backtranslate['H'] = {"CAT", "CAC"}

Please could someone specify and explain the correct syntax?

Thanks in advance!

You can do something like this:

map<char,vector<string>> backtranslate;
backtranslate['M'].push_back("ATG");
backtranslate['H'].push_back("CAT");
backtranslate['H'].push_back("CAC");

In Map, you can put as key or value, everything extends Object. But type argument cannot be of primitive type, char is a primitive Type. In place of char ou can use the type String.

Map begin by uppercase.

For add an element in Map, the method "put" exist.

A solution :

 Map<String, String[]> backtranslate = new HashMap<String, String[]>();
 backtranslate.put("M", new String[]{"ATG"});
 backtranslate.put("H", new String[]{"CAT", "CAC"});

Or (I prefer List, more easy to manipulate) :

Map<String, List<String>> backtranslate = new HashMap<String, List<String>>();
backtranslate.put("M", Arrays.asList("ATG"));
backtranslate.put("H", Arrays.asList("CAT", "CAC"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM