-4

I have been trying to make a dynamic array, and it just doesn't work, so I look for help at the internet, but I always see an answer saying that basically Java's array is always fixed, even if you can make it dynamic, you need to do some extra efforts... But then I think, why can't something like this works...

static int objCount = 0;

static int arrayCount = 1;

static Array[] myObject = new Array[arrayCount];

public static void main(String[] args) {

    addObject();
    addbOject();

    for(int i = 0; i < myObject.length; i++)
    {
        System.out.println(myObject[0].getSomething());
        System.out.println(arrayCount);
    }

}

public static addObject() {

// Variable instances of var A-C

myObject[objCount] = new Array(varA, varB, varC);
objCount = objCount++;
arrayCount = arrayCount++;

}

My addObject() method can't record the new object... Isn't it logically feasible...? Like everytimes the addObject() is invoked, it should increments objCount and arrayCount... I'm sure I missed something, any explanation will be much appreciated...

PS : I did give up and use arraylist instead

Rihanbook
  • 1
  • 1
  • `objCount++` and `arrayCount++` don't change the capacity of `myObject`. Calling `addObject()` enough times will cause an array index out of bounds exception. – ernest_k Jul 31 '18 at 08:00
  • There's a lot wrong with your code, ignore the fact that you're incrementing a mutable value and re-assigning the same value to it, the Array was not made to grow or shrink dynamically. Why exactly do you want the Array to grow to your liking? The ArrayList was specifically made to have a dynamic Array. – Zun Jul 31 '18 at 08:02
  • `++` operator is made to avoid that: `objCount = objCount++` – jhamon Jul 31 '18 at 08:03
  • Aside from your question: `objCount = objCount++` doesn't do what you think it does. `objCount++` first caches old value, then increments `objCount` but then expression returns cached old value which is then used for `objCount = ...` so effectively you are not changing anything. See: [What is x after “x = x++”?](https://stackoverflow.com/q/7911776) – Pshemo Jul 31 '18 at 08:07
  • As you read the size of an Array is fixed, so in your code you are basicly telling java to "Create me an array with the length of arrayCount=1". Whether you change arrayCount later on will not change the already created Array. It's like if you wrote "100km/h" on a sheet, went to a car dealer and told him to give you a car that drives that fast. If you were later to change that and write "1000km/h" on the sheet your car wouldn't suddenly transform into a faster one. You would still have the 100km/h fast car. – OH GOD SPIDERS Jul 31 '18 at 08:12

4 Answers4

2

Size of arrays in java is immutable(cannot be changes once declared). If you want to use dynamic arrays, Java provides Vector and ArrayList for this purpose. Read about it and use it(Much easier to use)

Vaibhav Singh
  • 177
  • 10
1

Arrays in Java are fixed. Period. To get around this problem, Lists were invented. There are many different implementations available and it depends on your needs which one you should choose.

ArrayList

Backed by an array.

Pros

  • Access times are O(1), therefore, ArrayLists are suitable for most cases, especially for iterations.

Cons

  • While adding items to the list has technically also a complexity of O(1), it may happen that the backing array must be enlarged if it was not big enough.
  • Removing items has a complexity of O(n)

LinkedList

A linked list is implemented by keeping a reference to the head and to the tail of the list. Each element keeps a reference to the next element.

Pros

  • Linked lists make it easy to add, remove or swap elements (everything is O(1))

Cons

  • Accessing an element in a linked list has a complexity of O(n) as one must read from the head of the list through all elements until the desired element is found. Linked lists are therefore more suitable for use cases with frequent write acces and few reads.

More information can be found here.

vatbub
  • 2,713
  • 18
  • 41
1

What is an array in your system?

A fixed block that you have allocated in your RAM.

Imagine it looks like this:

... | Y | A | A | A | A | Z | T | C | ...

Where A is the block you have allocated, then the other letters is foreign space and the pipes are separators (for clearance). This would imply you have only 4 places to insert a value. Even changing any positions you read a value from or place a value to, does never expand the array and you are still limited to those 4 positions.

Since other, foreign values might be stored directly after that, you have no chance of making it bigger. Instead, you need to allocate a NEW array, that was bigger then the one before to have enough room for the new values. And move all the values from the old to the new one.

The problem of your code:

You instantiate the array only once with size 1. This allocates only one position. Period. Whatever you do in your code never changes this (as pointed out before).

What happens with your code is:

  • An invocation of addObject(); adds the array element to the one and only slot you have.
    • objCount = objCount++; adds the old value of objCount to objCount (in other words: it doesn't do anything), then increments objCount by one. To eliminate the useless redundancy, replace objCount = objCount++; by objCount++; that applies it directly to the variable, you do not need to reassign it. That happens automatically.
  • A second invocation of addObject(); now tries to place a new element at slot 1 (note: Arrays begin with index 0 = slot 1). This will just overrride the old one.

Solution:

Many people had this problem before. Therefore different data structures have been developed in order to be able to cope with dynamic resizing arrays that can store something like a state (e.g. number of items).

In Java these data structures are called Lists. However you are good to go with using ArrayList for your purposes (basically it does already what you wanted). Other lists for specific use cases has Why can't we make dynamic array in java pointed out.

Akar
  • 534
  • 5
  • 6
-2

You would have to do, what ArrayList does internally:

  1. Allocate a new array with the desired size (usually 1.5 up to 2x of the size in order to minimize the chance that this happens too often)
  2. Copy the contents from your current array to the new array.
  3. Assign the new array to the old array's variable
Akar
  • 534
  • 5
  • 6