How to create a list in c # [closed]

0

How to make a generic list of your own without using List < & gt ;? To which I have come following some examples done in class but implemented in java:

public class ListaGenerica<E>
{

    private int size = 0;
    private E[] data;

    public ListaGenerica()
    {

    }
    public ListaGenerica(int size)
    {
        this.size = size;

    }
    public void sizeE()
    {
        data = (new object[size]);
    }
    public Boolean isEmpty()
    {
        return size == 0;
    }
    public E get(int i)
    {
        return data[i];
    }
    public void set(int i, E e)
    {
        data[i] = e;
    }
    public void add(int i, E e)
    {
        if (size == data.Length) // not enough capacity
        {
            MessageBox.Show("Array is full");
        }
        for (int k = size - 1; k >= i; k--) // start by shifting rightmost
         data[k + 1] = data[k];

        data[i] = e; // ready to place the new element size++;
    }
    public E remove(int i)
    {
        E temp = data[i];
        for (int k = i; k < size - 1; k++)
            data[k] = data[k + 1];
        data[size - 1] = default(E);
        size--;
        return temp;
    }

}
    
asked by Luis Ortiz 11.10.2017 в 04:04
source

1 answer

2

It is not clear why you want to implement something like List<T> if that class already exists. Regarding the error you have, you are never initializing data , you must do it in the constructors:

public ListaGenerica(int size)
{
    data= data = new E[size];
}

But you have another problem. Since you are using an array, in the constructor without parameters you could not initialize the object, since in C # an array must be instantiated with a fixed size. So you should do it with a size of 0:

public ListaGenerica()
{
    data= data = new E[0];
}

This clashes with your implementation of add , which in that case should resize the array to make room for the new element, doing something like this:

E[] newData = new E[tamaño];
Array.Copy(data, 0, newdata, 0, tamaño);
data = newData;

These are just a few strokes, but in these cases it is always better to see how the good ones do it. Here I leave the implementation of List of Microsoft, studying it you can learn what is the best way to implement your code: List Source Code

    
answered by 11.10.2017 / 09:18
source