Creating a dynamic array in java without using a collection

I was asked in an interview: "How to create a dynamic array without using any collection, such as ArrayList, vector, etc."

I said this is not possible because the array has a fixed size. They said no, maybe you need to write a program to answer this question.

I could not answer this question. They gave me one hint to “use generics,” although it seems very difficult to answer this question. Can anyone help me out?

+4
source share
4 answers

. default_size, n = 10 (), load_factor = 0.75 ()

T[] array = (T[])new Object[DEFAULT_SIZE];

index .

index > n*load_factor , , index < n*load_factor ( , ) .

public class CustomArrayList <T> {
  private int index = 0;
  private final int DEFAULT_SIZE = 10;
  private final double DEFAULT_LOAD = 0.75;
  private T[] array;

  public CustomArrayList(){
    array = (T[])new Object[DEFAULT_SIZE];
  }

  public void add(T elem){
    if(index>=array.length*DEFAULT_LOAD){
        array = Arrays.copyOf(array, array.length+10);
    }
    array[index++]=elem;
  }
}
+4

Java? : , , . , , . .

1000 .
, , 100 .
:
n , 1000 × + 100 × (1 + 2 + ,, + ( - 1)) = 1000 k + 50k (k-1) k, n.

1000 , , .
  : 1000 × (1 + 2 + 4 + ··· + 2 ^ ( - 1) ) = 1000 × (2 ^ - 1) & ; =
: 1000 × (1 + 1 + 2 + 4 + ··· + 2 ^ ( - 1) ) = 1000 × 2 ^ =
, n, .
, , .

0

. - , . , , ...

:

public class DynamicArr {//method to increase size dynamically during runtime

    public static int[] incrSize(int arr[]) {
        int len = arr.length;
        int newArr[] = new int[len+1]; //increasing the length of the current array in an other temporary array
        return newArr; // returning the new array

    }

    public static void main(String... strings) {
        int a[] = new int[10];
        System.out.println("Size Before Increase: " + a.length);
        a = incrSize(a); // pointing the reference to the new array by calling the incrSize() method
        System.out.println("Size After Increase: " + a.length);

    }

}

, . .

, ...

0

. , , "" , get(int index) set(T value, int index) size.

" " , :

Holder<T> {
   T[] array = (T[])new Object[10]; // 10 just as an example  
}

, , T[] array = new T[10], , java ( @SafeVarArgs ). , , ; , .

, add(T value), . , , Arrays.copyOfRange System.arrayCopy .

, T (look for generics bounds).

, delete ? null? ? , ? , - ? (: java , : ArrayList#trimToSize())

When your inner array is full and you want to add another element, how much would you expand it? 50%, 75%? Or enough space for one item? If you knew how jdk's internal collections work, the answer would be very simple.

I think this is not a bad question for interviews in all IMOs.

0
source

Source: https://habr.com/ru/post/1692454/


All Articles