Question

There seems to be a problem in add method of the class I have written.. I want to make a SortedList using an array, but I can't figure out what the problem is. This is my code:

public class SortedList {

    private Integer[] elements;
    private int size;
    private int capacity;

    public SortedList(int cap) {

        elements = new Integer[cap];

        if (cap > 0)
        {
            cap = capacity;
        }
        else
            capacity = 10;

    }

    public boolean isEmpty()
    {
        return size == 0;
    }

    public boolean isFull()
    {
        return size == capacity;
    }

    public int size()
    {
        return size;
    }

    public void doubleCapacity()
    {
        capacity = capacity * 2;
    }

    public void add(Integer el)
    {
        if(this.isEmpty())
        {
            elements[0] = el;
            size++;
        }

        else if(this.isFull())
        {
            this.doubleCapacity();
            for(int i = 0; i<this.size(); i++)
            {
                if(el >= elements[i])
                {
                    elements[i+2] = elements[i+1];
                    elements[i+1] = el;
                }

                else
                {
                    elements[i+1] = elements[i];
                    elements[i] = el;
                }
            }
            size++;
        }
        else
        {
            for(int i = 0; i<this.size(); i++)
            {
                if(el >= elements[i])
                {
                    elements[i+2] = elements[i+1];
                    elements[i+1] = el;
                }
                else
                {
                    elements[i+1] = elements[i];
                    elements[i] = el;
                }
            }
            size++;
        }

    }

    public String toString()
    {
        String s = "";
        s = s + "<SortedList[";
        for(int i = 0; i < this.size(); i++)
        {
            s = s + elements[i];
            if(i < this.size()-1)
                s = s + ",";
        }
        s = s + "]>";
        return s;
    }


    public static void main(String[] args)
    {
        SortedList sl = new SortedList(5);
        sl.add(3);
        //sl.add(2);
        sl.add(4);
        sl.add(5);
//      sl.add(6);
        System.out.println(sl.toString());
    }



}

My code works if I only add 2 Integers to my list, but when I try to add the numbers 3,4,5 then I get 3,5,5...

What can be the problem? Thanks..

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top