Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

how to add elements into array JAVA?

im creating a class myVector that has all the methods of the vector, but these methods must be implemented using array, i have constructor

int[] array;

public MyVector()

{

array = new int [5];

}

and the method to add elements into my vector

public void add(int element) {

for(int i=0; i<array.length; i++){

array[i] = element;

}

the problem is that i cant add several elements into this array

MyVector mv = new MyVector();

mv.add(2);

mv.add(3);

mv.add(4);

the answer will be

4

4

4

4

4

but i cannot use ArrayList or just ready methods of vector, and how can do my array resizeable? Thank you in advance!

4 Answers

Relevance
  • 10 years ago
    Favorite Answer

    You should construct a zero length array. Then each time you add you define a temp that's 1 larger, copy, and set the last element:

    public myVector() {

    arr = new int[0];

    }

    public void add(int ele){

    int[] temp = new int[arr.length+1];

    for( int k=0;k<arr.length;k++)temp[k]=arr[k];

    temp[temp.length-1]=ele;

    this.arr = temp;

    }

    This has been tested and it works just fine. There's actually a better way to copy that array but this is simply for a newbie.

  • 10 years ago

    The reason your array ends up with all 4s is because of the for loop you use to add to the array

    You add each element (int) to every slot in the array. Because the array length is five you add 4 five times overwriting the 3 and 2 which were also added five times.

    for(int i=0; i<array.length; i++){

    array[i] = element;

    }

    If the maximum number of element you need to allow for is 5 (per your array initialisation) then add a counter

    int counter = 0 ; //outside the method public void add(int element) {

    and each time you add an element, rather than using a for loop, so kill the for loop, just use

    array[counter] = element;

    counter++;

    That will progressively add each element to the next slot in the array. HOWEVER, if you attempt to add more than five elements you will get an index out of bounds error because you will be trying to add six or more elements to an array initialized at five.

    Be safe, be sage

  • 10 years ago

    You have declared your array a

    In its 6th slot. Try removing the 5... Make it look like: array = new int[]

    Source(s): Computer Scientist and Technician
  • 10 years ago

    remove [5] just type: array=new int

Still have questions? Get your answers by asking now.