1

次のように、学生オブジェクトを保持する ArrayList を取得しました。

List<Students> stdList = new ArrayList<Students>();
stdList.add(new Students(1,"std1","address1"));
stdList.add(new Students(2,"std2","address2"));
stdList.add(new Students(3,"std3","address3"));
stdList.add(new Students(4,"std4","address4"));
stdList.add(new Students(5,"std5","address5"));
stdList.add(new Students(6,"std6","address6"));
stdList.add(new Students(7,"std7","address7"));
stdList.add(new Students(8,"std8","address8"));

ここで、stdList を、この場合は 4 と等しい数の学生を含む 2 つのグループに分割し、それらを次の方法で達成した hashMap に追加する必要があります。

 int j=0;
 HashMap<Integer,List<Students>> hm = new HashMap<>();
    for (int i = 0; i < stdList.size(); i = i + 4) 
  {
     j++;
     hm.put(j,stdList.subList(i, i + 4));

  }

ハッシュマップには、キーと値のペアが次のように含まれるようになりました。

{1=[1 std1 address1, 2 std2 address2, 3 std3 address3, 4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8]}

ここで、次のように「3 std3 address3」という値を「キー 1」から「キー 2」に移動する必要があります。

{1=[1 std1 address1, 2 std2 address2,  4 std4 address4], 2=[5 std5 address5, 6 std6 address6, 7 std7 address7, 8 std8 address8,3 std3 address3]}

どうすればこれを達成できますか?

4

5 に答える 5

2

「someKey」が削除するキーであると仮定すると、

key1.put(someKey, key2.remove(someKey));
于 2013-10-31T12:50:11.190 に答える
0

このようにすることができます。

 Student stud3=myMap.get(1).remove(myMap.get(1).get(2));
 List<Student> secondList=myMap.get(2);
 secondList.add(stud3);
 myMap.put(2,secondList);

myMap はあなたが作成した地図です。

于 2013-10-31T12:56:35.650 に答える
0
List<Student> ls = hm.get(1);
Student st  = ls.get(3);
ls.remove(st); hm.get(2).add(st);

インデックスでアクセスできる場合は、リストを検索する必要はありません。

于 2013-10-31T12:49:35.693 に答える
0

解決策は、HashMap から生徒のリストを取得し、移動する Student オブジェクトを削除することです。次に、HashMap から他のリストを取得し、オブジェクトを追加するだけです。

以下のコードは実行しませんでしたが、次のようになります

//Get the list for Key 1
List<Students> list = hm.get(Integer.valueOf(1));

//Remove the 3rd value, that would be your "3 std3 address3"
Students std = list.remove(2);

//Now get the list of Key 2
list = hm.get(Integer.valueOf(2));

//Add the value to that list
list.add(std);
于 2013-10-31T12:50:52.843 に答える