1

ループ内の変数に基づいた名前を使用して、while ループ内で Arraylist を作成する必要があります。ここに私が持っているものがあります:

while(myScanner.hasNextInt()){    

    int truster = myScanner.nextInt();
    int trustee = myScanner.nextInt();
    int i = 1;
    String j = Integer.toString(i);
    String listname = truster + j;

    if(listname.isEmpty()) {
        ArrayList listname = new ArrayList();
    } else {}
    listname.add(truster);

    i++;
}

変数 truster はスキャン中に複数回表示されるため、if ステートメントは arraylist が既に存在するかどうかを確認しようとしています。しかし、私はそれを順不同で行ったかもしれないと思います。

ご協力いただきありがとうございます!

4

3 に答える 3

6

ArrayLists を Map に格納します。

Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){    
    // Stuff
    List<String> list = new ArrayList<String>();
    list.add(truster);
    listMap.put(listname, list);
}

ジェネリック ( のビット) を使用して、およびに含めることができる<>オブジェクトの型を定義していることに注意してください。ListMap

Mapを使用して格納されている値にアクセスできます。listMap.get(listname);

于 2012-11-19T20:51:16.997 に答える
1

本当に何を意味するのかまったくわかりませんが、コードに深刻な根本的な欠陥がいくつかあるので、それらに対処します.

//We can define variables outside a while loop 
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();

//i is not a "good" variable name, 
//since it doesn't explain it's purpose
Int count = 0;

while(myScanner.hasNextInt()) {    
    //Get the truster and trustee
    Int truster = myScanner.nextInt();
    Int trustee = myScanner.nextInt();

    //Originally you had:
    // String listname = truster + i;
    //I assume you meant something else here 
    //since the listname variable is already used

    //Add the truster concated with the count to the array
    //Note: when using + if the left element is a string 
    //then the right element will get autoboxed to a string

    //Having read your comments using a HashMap is the best way to do this.
    ArrayList<String> listname = new ArrayList<String>();
    listname.add(truster);
    trusterMap.put(truster + count, listname);
    i++;
}

さらに、配列に供給される Int のストリームを myScanner に格納していますが、それぞれの意味は大きく異なります (trusterおよびtrustee)。ファイルまたはユーザー入力からこれらを読み込もうとしていますか? これを処理するためのより良い方法があり、あなたが何を意味するかについて以下にコメントすると、提案された解決策で更新されます.

于 2012-11-19T20:54:33.510 に答える
1

私があなたを正しく理解している場合は、リストのリストを作成するか、さらに良いことに、キーが必要な動的な名前で、値が新しく作成されたリストであるマップを作成してください。これを別のメソッドでラップして、 のように呼び出しますcreateNewList("name")

于 2012-11-19T20:51:19.650 に答える