ArrayList: Is this right or does it have a better way to do it?

2

I know a little bit of java, but now I'm venturing into C #, but here's a question: In Java we instantiate an ArrayList like this:

ArrayList<Tipo> nomeArray = new ArrayList<>();

We retrieved a value like this:

nomeArray.get(1).getNome();

And by my testing here with C #, it looks like this:

ArrayList nomeArray = new ArrayList();//Não declara o tipo, estranho

And it looks like it recovers like this:

((Tipo) nomeArray[1]).Nome;//Toda vez que tenho que recuperar tenho que usar um TypeCast?

Is this the right way? Or is it better?

    
asked by anonymous 30.09.2017 / 16:52

1 answer

2

In C # you should use the type List<tipo> that works basically like the ArrayList in Java.

In C # the ArrayList is marked as obsolete.

ArrayList was available before generics were implemented in .NET 2.0.

There is no advantage in ArrayList. I see that generics are widely used by developers. I recommend using List<> or other types of collections or generic lists.

Example:

List<Tipo> variavel = new List<Tipo>();
variavel.add(variavelDoTipo);

var recuperaValor = variavel[0];

List uses the add() method to add an element to the collection. (The type must match the list type.)

To retrieve the value, you use the syntax of accessing a common array.

Example:

var variavel = nomeLista[0];
    
30.09.2017 / 17:12