- Home /
list.Add is replacing
Im trying to generate a list of lists of lists of ints List<List<List<int>>>();
. But every time it is suppose to add, it is replacing all items before.
int numeroDeInputs = 2;
int numeroDeOutputs = 2;
int numeroDeCamadas = 6; //layers
List<int> genes;
List<List<int>> GeneList;
List<List<List<int>>> genotipo;
void Start()
{
genotipo = new List<List<List<int>>>();
GeneList = new List<List<int>>();
genes = new List<int>();
StartGenotipo();
PrintGenotipo();
}
void StartGenotipo () {
genotipo.Clear();
for (int i = 0; i < numeroDeCamadas-1; i++)
{
GeneList.Clear();
int tamanhoDoProx = numeroDeCamadas - i - 2 + numeroDeOutputs; //size of next layer
for (int j = 0; j < tamanhoDoProx+1; j++)
{
genes.Clear();
for (int k = 0; k < tamanhoDoProx; k++)
{
genes.Add(Random.Range(0, tamanhoDoProx - 1));
}
GeneList.Add(genes);
}
genotipo.Add(GeneList);
}
}
void PrintGenotipo()
{
string retorno = "";
foreach (List<List<int>> lsLsI in genotipo)
{
retorno += "\n(";
foreach (List<int> lsI in lsLsI)
{
retorno += "\n[";
foreach(int num in lsI)
{
retorno += num;
}
retorno += "]";
}
retorno += ")";
}
Debug.Log(retorno);
}
it should output in the console something like:
([015031][012350][130350])
([01234][42023][01210])
([0033][1020][1230])
([002][012][110])
([01][10][11])
instead of
([00][00][00])
([00][00][00])
([00][00][00])
([00][00][00])
([00][00][00])
Answer by Bonfire-Boy · Dec 05, 2018 at 06:08 PM
When you add a list to a list, it adds a reference, not a copy. You're not making a List of lists of lists at all, you're making a list of multiple references to the same list (...of multiple references to the same list.. etc).
So there are 2 fixes that spring to mind. You could try replacing
genes.Clear();
with
genes = new List<int>();
(and so on)
Alternatively, you could change your Add(list) calls so that they're adding a copy.
A List is an object. How many List objects do you create? You create exactly 3:
genotipo = new List<List<List<int>>>();
GeneList = new List<List<int>>();
genes = new List<int>();
All those 3 lists are empty in the beginning. When you do
GeneList.Add(genes);
The GeneList will contain one element, that is a reference to the genes list. There are still only those 3 lists you have created so far. Objects don't magically multiply itself. Objects need to be created with "new".
Bonfire has explained it already quite well. If you have still trouble understanding what's happening i strongly recommend to look up some basic C# / program$$anonymous$$g resources. Understanding what a reference type is is an absolutely crucial detail.
Your answer
Follow this Question
Related Questions
Checking a list containing another list, and checking if the elements in the list are equal problem 1 Answer
How can the first C# script get the second C# script data? 1 Answer
iterate through two lists element by element 1 Answer
Networking Buttons and Syncvar 1 Answer
How to make a gun autoaim on targets under the reticule? 0 Answers