2

形式で辞書を作成しようとしてい<K, List<V>>ます。

private static Map<String, Collection<String>> dict = new HashMap<String, Collection<String>>();

互換性のないデータ型エラーを使用new HashMap<>();またはnew HashMap<String, ArrayList<String>>();スローします

以下のような辞書が必要です。

a: apple, ajar, axe, azure
b: ball, bat, box
d: dam, door, dish, drown, deer, dare
u: urn, umbrella
y: yolk

これを行うには、以下のコードを書きます。put() は、互換性のないパラメーターのコンパイル エラーを返します。この例で put() を使用する正しい方法は何ですか?

dict.put("a", "apple");
dict.put("a", "ajar");
.
.
.
dict.put("u", "umbrella");
dict.put("y", "yolk");
4

6 に答える 6

7

リストを値としてマップに配置する必要があります。次に例を示します。

List<String> listA = Arrays.asList("apple", "ajar", "axe", "azure");
dict.put("a", listA);

または、複数の値を特定のキーにマップできるguava Multimapを使用できます。

于 2013-07-24T14:28:25.603 に答える
1

必要なのはこれです。

    List al = new ArrayList<String>();
    al.add("apple");
    al.add("ajar");

    HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
    hm.put("a", al);

    System.out.println(hm.get("a"));

これは、使用するときに;

private static Map<String, Collection<String>>

リストのようなコレクションが必要です。オブジェクトを文字として挿入しないでください

于 2013-07-24T14:31:14.410 に答える
1

あなたが行った定義に従うことしかできません: Map<String, Collection<String>>a が String であり、 ba である dict.put(a,b) を使用することを意味しますCollection

あなたの問題である値として文字列を入れようとしています。あなたはそのようなことをしたいかもしれません:

Collection col = dict.get("a");
if (col == null) {
  col = new ArrayList();
}
col.add("apple");
dict.put("a",col);
于 2013-07-24T14:31:23.353 に答える
1

Map<String, Collection<String>>これは、Map 宣言のようにarrayList を値に入れる必要があるためですMap<String, String>

 ArrayList<String> list = new ArrayList<String>();
 list.add("apple");
 dict.put("a",list );

Java 7 に従って、ダイヤモンド演算子を使用してそれを実行できるため、次のようにマップを作成できます。

List<String, List<String>> = new ArrayList<>();
于 2013-07-24T14:30:11.130 に答える
1

最初に辞書のタイプを次のように変更します

private static Map<Character, ArrayList<String>> dict = new HashMap<>();

ジェネリックは共変ではないため、配列リストを簡単に配置できます。

文字ごとに、次を作成します。

ArrayList<String> myList=new ArrayList<>();

そしてput()それは口述する

dict.put(myList);

次に、次のように単語を追加できます。

dict.get(letter).put(word);
于 2013-07-24T14:30:12.307 に答える