我有单个列表。我填充他,然后把他放到地图上。然后我清理列表,再次填充他,并将他放在不同键下的相同地图中。如此循环答案。
Map<String, List<MyClass>> map = new HashMap<>();
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(id_1));
map.put("key_1", list);
list.clear();
list.add(new MyClass(id_2));
map.put("key_2", list);
//map is = {key_1:id_2, key_2:id_2}
//Why map is NOT = {key_1:id_1, key_2:id_2}
为什么看起来地图会引用列表而不是列表的新副本?
答案 0 :(得分:1)
您要将相同的列表引用添加到地图中:&#34; key_1&#34;和&#34; key_2&#34;两者都指向相同的#include <iostream>
using namespace std;
struct Build
{
int number;
string size;
char wall_type;
};
int searchArray(const int [], int);
int main ()
{
int result, // Index of array that matches search
value; // The house number entered by user
Build house[5] = {
{1, "big", 'F'},
{3, "small", 'D'},
{5, "tiny", 'A'},
{7, "huge", 'B'},
{9, "medium", 'F'}
};
for (int i = 0; i < 5; i++) // Just a test to see if the
{ // array is populated correctly
cout << house[i].number << " "
<< house[i].size << " "
<< house[i].wall_type << endl << endl;
}
cout << "Enter the house number: ";
cin >> value;
result = searchArray(house.number, value);
if (result == -1)
cout << "Not found." << endl;
else
{
cout << "Index number: " << result << endl
<< "House number: " << house[result].number << endl;
}
return 0;
}
/***************************************************************
*
* This function searches an array of integers to find a match
* entered by the user. It works great if you are just dealing
* with a single array but I can't figure out the syntax to
* search just one member of a struct in an array of structs.
* Please help!
*
*/
int searchArray(const int list[], int value)
{
int index = 0;
bool found = false;
int position = -1;
while (index < 5 && !found)
{
if (list[index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
对象。您需要做的是根据第一个列表创建第二个列表:
List
答案 1 :(得分:1)
这就是Java的工作方式。如何放入地图是对列表的引用。如果要复制列表,则需要明确地执行此操作。
List<MyClass> copy = new ArrayList<>(list);
答案 2 :(得分:1)
当您执行map.put(“key_2”,list)时,您将对列表对象进行引用。 您必须实例化另一个列表对象。