Jump to content

Insertion of new element in Array

- - - - -

  • Please log in to reply
5 replies to this topic

#1
OwsumEmam

OwsumEmam

    Newbie

  • Members
  • Pip
  • 7 posts
I want to know how to insert a new element in Array. I tried but could not succeed. I failed in indexing the new location to Array because Array is of fixed size.
So can you please give the simple example so that I can learn.

#2
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts

String[] arrayofstrings = new String[3];

arrayofstrings[0] = "we";

arrayofstrings[1] = "something";

arrayofstrings[2] = "bla";


If you want to insert an item after the limit, you can't, you have to recopy your array in a bigger array, there's a class that can do that for you : Vector.


import java.util.Vector;


Vector<String> strings = new Vector<String>();

strings.add("bla");

strings.add("wefw");

strings.add("etc");



#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Without List kind of classes:

import java.util.Arrays;


public class SomeClass{

    int[] intArray;


    public void addNumber(int number){

        intArray = Arrays.copyOf(intArray, intArray.length+1);

        intArray[ intArray.length-1 ] = number;

    }


}



#4
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
A Vector would be more efficient than the snippet from wim DC because the Vector class does not recopy the array every time you add a item. The way it works, when you add an item, it doubles the size of the array. I'm sure you could easily update his little snippet.

#5
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP

Simonxz said:

A Vector would be more efficient than the snippet from wim DC because the Vector class does not recopy the array every time you add a item. The way it works, when you add an item, it doubles the size of the array. I'm sure you could easily update his little snippet.

It is true that it is more efficient to NOT copy the array every time you add an element to the array.

However...
When the objects inside of vector reach initial Capacity +1 the array is doubled and the original array also has to be copied.

If you know more-or-less how many elements the array will contain before-hand, then you have a better chance of knowing what kind of array you should use.

#6
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
It's no secret using a array will always be more efficient than using a vector but his question was about adding an item after the initial capacity is reached




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users