Solidity Arrays – Inserting Objects at Specified Position

arrayssolidity

I have following code piece:

  struct PaymentReceipt{
    uint   start_block;
    uint   end_block;
  }
  PaymentReceipt[] paymentReceiptList;

  function verfiyPayment(uint block_start, uint block_end) returns (bool success) {
    paymentReceiptList.push(PaymentReceipt({start_block: block_start, end_block: block_end }));
    return true;
  }

As I know, each new Struct will be pushed on top of the stack, so latest element (paymentReceiptList.length) will always point to the latest pushed Struct.

https://github.com/ethereum/wiki/wiki/Solidity-Features:

Dynamically-sized storage arrays have a member function push, such
that var l = arr.push(el); is equivalent to arr[arr.length++] = el;
var l = arr.length;.

For example, Java has following approach that: we can insert the specific element at the specified position in the list.

[Q] Is it possible to push an object into an Array with a given index and shift indexes, like the example on Java?

Best Answer

There is no built-in method for inserting a value at a specific position in an array. You'll just have to write a loop to do it.

If you're going to be inserting a lot of elements in the middle of the array, it may make more sense to use a linked list instead of an array, so that you aren't doing as many storage writes, which can be expensive.

Related Topic