简体   繁体   English

自动增量数组java

[英]Automatic increment array java

Hello I have got this basically fully working sorted vector , the problem here is however that I can only initialize the array to a fixed size before inserting any values , so for example I can initialize 5 but if I want to insert 6 items it gives me a null pointer exception . 您好,我有这个基本上可以正常工作的排序向量,但是这里的问题是,我只能在插入任何值之前将数组初始化为固定大小,例如,我可以初始化5,但是如果我想插入6项,它将给我空指针异常。 I think I do understand what is happening however I would like anybody to show me a solution how the array size can be increased automatically every time I want to insert something . 我想我确实了解发生了什么,但是我希望任何人都可以向我展示一个解决方案,该方法是每次我想插入一些东西时如何自动增加数组大小。 ( Without having to use any inbuilt java functionalities like ArrayList ) (而不必使用任何内置的Java功能,例如ArrayList)

Thank you 谢谢


package ads2;

public class SortedVector2
{
    private int length;
    private int maximum;
    private int growby;
    private int temp; 
    private int x = 0;        
    private int high;   
    private int middle; 
    private int low;  


    String[] data;

    public SortedVector2() 
    {

        length = 0;

        maximum = 5;
        data = new String[maximum];


    }

    public void AddItem(String value) 
    {

        /*if (length == maximum)    
        {
        maximum += 200000;
        */

        data[length] = value;

        length++;
      //  SetSorted();
       // SetSorted(data);

    }

    public void SetSorted() 
    {

        for (int j = 0; j < data.length - 1; j++) {
           if (data[j].compareTo(data[j + 1]) > -1) {
                String temp = data[j];
                data[j] = data[j + 1];
                data[j + 1] = temp;
            }

       }
        for (String s : data) {
         System.out.println(s);
       }

       // private String[] data;

        /*
       for(int i = data.length-1; i >= 0; i--) {
       for(int j = 0; j < i; j++) {
        if(data[j].compareTo(data[j + 1]) > -1) {
            String temp = data[j];
            data[j] = data[j + 1];
            data[j + 1] = temp;
        }
       }
      }  for (String s : data) {
        System.out.println(s);
    }
                */
    }

    public void SetGrowBy(int growby)     
    {
       maximum += growby;
    }


    public int GetCapacity() 
    {
        return maximum;
    }


    public int GetNoOfItems() 
    {
        return length;
    }


    public String GetItemByIndex(int index) 
    {
        return data[index];
    }

     public int FindItem(String search)
     {

         for (x=0;x<=length; )
         {
            middle =((low + high)/2);
            if (data[middle].compareTo(search)==0)
            {
                return middle;
            }
            else if (data[middle].compareTo(search)<0)  
            {       

               low = middle;
               x++;
               return FindItem(search);
            }
            else
            {

               high = middle; 
               x++;
               return FindItem(search);
            }
     }
     return -1;
    }

    public boolean Exists(String search) 
    {
        boolean output;

        int y;
        y = 0;

        while (data[y] != search && (length - 1) > y)
        {
            ++y;
        }

        if (data[y] == search) 
        {
            output = true;
        } else 
        {
            output = false;
        }

        y = 0;

      return output; 

    }

    public void InsertItem(int index, String value) 
    {
        if (length == maximum) 
        {

        maximum += 200000;

        }

        for(int i = length - 1; i >= index; --i) 
        {

            data[i + 1] = data[i];

        }

        data[index] = value;

        length++;
    }


    public void DeleteItem(int index) 
    {
       for(int x = index; x < length - 2; ++x) 
       {

            data[x] = data[x + 1];

        } 

       length--;
    }

    public String toString()
    {
        String res = "";


        for (int i=0; i<length; i++)
            res+=data[i] +  "; ";

        return res;
    }

}

To increase array size dynamically use Collection framework interface List , It has implementation ArrayList , Vector and LinkedList use any one in them. 要使用Collection框架接口List动态增加数组大小,它具有ArrayListVectorLinkedList实现,可以使用其中的任何一个。

Or, Simply create copyArray(String[]) api which will give you array with increased capacity. 或者,只需创建copyArray(String[]) api,它将为您增加容量。

public String[] copyArray(String[] oldArray){
  int capacity = oldArray.length * 2;
  return Arrays.copyOf(oldArray, capacity);
}

String[] data = copyArray(data) // pass array 

You have to do what the implementers of ArrayList did. 您必须执行ArrayList的实现者所做的事情。 When you try to add an element when the array is full, you create a larger array, copy the existing elements to it and add the new element. 当您尝试在数组已满时添加元素时,将创建一个更大的数组,将现有元素复制到该数组中并添加新元素。

I think you've got all the basic variables you need to do what you need to do: just check if the size equals the capacity when you are adding an item and if it does reallocate the array: 我认为您已经具备了执行基本操作所需的所有基本变量:只需在添加项目时检查大小是否等于容量,以及是否确实重新分配了数组即可:

if (size == capacity) {
    capacity += growby;
    data = Arrays.copyOf(data, capacity);
}

That's pretty much all ArrayList does. 这几乎是ArrayList所做的所有事情。

You need to re-allocate when increasing the size of the data buffer, for example, 当增加数据缓冲区的大小时,您需要重新分配,例如,

public void InsertItem(int index, String value) 
{
  String[] data2;
  if (length == (maximum-1))
  {
    maximum += 5; // increment size in lot of 5
    data2 = new String[maximum);
    for (int ii = 0; ii < length; ii++) 
    {
      data2[ii] = date[ii];
    }
    data = data2; // re-assign with increased size
  }
  for(int i = length - 1; i >= index; --i) 
  {
    data[i + 1] = data[i];
  }
  data[index] = value;
  length++;
}

In software engineering there is a saying, " Don't reinvent the wheel " - which emphasizes us on using the existing archetype. 在软件工程中,有一种说法是“ 不要重新发明轮子 ”,它强调了我们在使用现有原型时的作用。 Because they are tested and used by for long period of time. 因为它们经过长时间的测试和使用。 So it's better to use ArrayList for regular/professional purpose. 因此,最好将ArrayList用于常规/专业用途。

But it if it is for learning purpose then you can chose any one from the previous answers. 但是,如果这是出于学习目的,那么您可以从以前的答案中选择任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM