Java Dynamic arrays -


i taking programming class java , need dynamic arrays. have looked around , can't find ways on level of simplicity. not far in class , learned basics don't know need know how make dynamic array.

here 2 sample programs given:

public class dynamicarrayofint {     private int[] data;     public dynamicarrayofint()     {         data = new int[1];     }     public int get(int position)     {         if (position >= data.length)             return 0;         else              return data[position];         }     public void put(int position, int value)     {         if (position >= data.length)         {             int newsize = 2 * data.length;             if (position >= newsize)                 newsize = 2 * position;             int[] newdata = new int[newsize];             system.arraycopy(data, 0, newdata, data.length);             data = newdata;             system.out.println("size of dynamic array increased " + newsize);         }         data[position] = value;     } } ` 

number 2

import java.util.scanner; public class reversewithdynamicarray {     public static void main(sting[] args)     {         dyanamicarrayofint numbers;         int numct;         int num;         scanner scan = new scanner(system.in);         numbers = new dynamicarrayofint();         numct = 0;         system.out.println("enter postive integers; enter 0 end");         while (true)         {              num = scan.nextint();             if (num <= 0)                 break;             numbers.put(numct, num);              numct++;         }         system.out.println("\nyour numbers in reverse order are:\n");         (int = numct - 1; >= 0; i--)         {             system.out.println( numbers.get(i) );         }     } } 

the second 1 supposed inherit first , allow create more arrays once typed in. when use these says have error , says class names reversewithdynamicarray accepted if annotation processing explicitly requested.

use 1st sample program, changed parameters @ system.arraycopy

public class dynamicarrayofint { private int[] data; public dynamicarrayofint() {     data = new int[1]; } public int get(int position) {     if (position >= data.length)         return 0;     else          return data[position];     } public void put(int position, int value) {     if (position >= data.length)     {         int newsize = 2 * data.length;         if (position >= newsize)             newsize = 2 * position;         int[] newdata = new int[newsize];         system.arraycopy(data, 0, newdata, 0, data.length);         data = newdata;         system.out.println("size of dynamic array increased " + newsize);     }     data[position] = value; } } 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -