Auto expand my array
hi all, i am creating an dynamic array...in order word, my array wil expand automatically if the data storing in it reach to it`s maxmium capacity....i implement a ensureCapacity to expand my array if the "numberUsed " for my array >= the "maxNumberOfElement " for my array..but ..i get a wired result...could anyone give me some suggestion...thx a lot
//For simpification, i try to set my array to to be allow 3 maximum only
//it would increment one to one of my varible "numberUsed" if i add one element to my array .
//it keeps incrementing til reaching to my maxNumberElements ,which is 3 now.
//so, if the numberUsed > maxNumberElements, it mean it is an full array.
//At that time, i try to call my ensureCapacity fucntion to double my orginal array.
//but, i got the following problem when i execute it
//>java MyArray
//java.lang.NoSuchMethodError: main
//Exception in thread "main" >Exit code: 1
//>javac MyArrayDemo.java
//>Exit code: 0
//>java MyArrayDemo
//testing the value that is fit to my current array
//Error: Adding to a full array...Calling an ensureCapacity
//0
//1
//2
//4<< missing 3 here ...why ?
//>Exit code: 0
////////////////////////////////////
//What`s wrong with my code
//the result should be
//
//0
//1
//2
//3
//4
publicclass MyArray<T>
{
privateint maxNumberElements;//Same as a.length
private T [] a;
privateint numberUsed;//Number of indices currently in use
//set the maximum number of allowable elements to 3
MyArray()
{
maxNumberElements = 3;
//a = new T[ maxNumberElements ];
a = (T[])new Object[maxNumberElements];
numberUsed = 0;
}
//Precondition arraySize > 0
MyArray(int arraySize)
{
if(arraySize < 0)
{
System.out.println("Error Array size zero or negative.");
System.exit(0);
}
maxNumberElements = arraySize;
//a = new T[ maxNumberElements ];
a = (T[])new Object[maxNumberElements];
numberUsed = 0;
}
MyArray(MyArray<T> original)
{
if(original ==null)
{
System.out.println("Fatal Error: aborting program.");
System.exit(0);
}
maxNumberElements = original.maxNumberElements;
numberUsed = original.numberUsed;
for(int i = 0; i < numberUsed; i++)
a[i] = original.a[i];
}
publicvoid add(T newElement)
{
if(numberUsed >= a.length)
{
System.out.println("Error: Adding to a full array...Calling an ensureCapacity");
ensureCapacity(numberUsed*2 +1);
//stem.exit(0);
}
else
{
a[numberUsed] = newElement;
numberUsed++;
};
}
//pls help me check here
publicvoid ensureCapacity(int newCapacity)
{
/*
if( newCapacity < numberUsed )
return;
*/
T[] old = a;
a = (T[])new Object[newCapacity];
for(int i = 0; i < numberUsed ; i++)
{
a[i] = old[i];
}
}
publicvoid remove(int index)
{
if( index < 0 || index >= numberUsed)
{
System.out.println("Error: illegal or unused index.");
System.exit(0);
}
//i am trying to delete in position index. Move down all element with indicex highter than the delete element.
for(int i = index; i < numberUsed -1 ; i++)
{
a[i] = a[i+1];
}
numberUsed--;
}
publicint search(T searchString)
{
for(int i=0; i < numberUsed; i++)
{
if(a[i] == searchString)
return i;
}
return -1;
}
public T retrieve(int index)
{
if(index < 0 || index >= numberUsed)
{
System.out.println("Error: illegal or used index.");
System.exit(0);
}
return a[index];
}
public String toString()
{
String theString =" ";
if(numberUsed <= 0)
{
theString ="\nThere is no Data. ";
}
else
for(int index = 0; index < numberUsed; index++)
theString +="\n" + a[index].toString();
return theString;
}
publicboolean empty()
{
return (numberUsed == 0);
}
publicboolean full()
{
return (numberUsed == maxNumberElements);
}
publicint getMaxCapacity()
{
return maxNumberElements;
}
publicint getNumberOfElements()
{
return numberUsed;
}
}
my testing driver
import java.io.*;
publicclass MyArrayDemo
{
//public static final int MAX_NUMBER_SCORES = 10;
publicstaticvoid main(String[] args)throws IOException
{
ReadOperation theRo =new ReadOperation();
ErrorCheckingOperation theEco =new ErrorCheckingOperation();
int readUser;
int theRemoveIndex;
MyArray<Integer> S =new MyArray<Integer>();
System.out.println("testing the value that is over to my current array ");
for(int i = 0; i <5; i++)// working fine if i assign a value that is fit to my array
{
S.add(i);
}
System.out.println(S.toString());
//readUser = theRo.readInt("Please enter the index of the array that u are going to remove from.\n" );
//theRemoveIndex = S.search(readUser);
//System.out.println("You have already remove element " + readUser + " which\nlocated in index " + theRemoveIndex + " in our array.");
//S.remove(theRemoveIndex);
//S.retrieve(theRemoveIndex);
//System.out.println(S.toString());
}
}
[11306 byte] By [
Ivan1238a] at [2007-11-27 6:20:28]

Hey,
the ensureCapacity code you posted was fine..
I am not sure I understand what is wrong. Take a look at this:
import java.io.*;
public class MyArrayDemo
{
public static final int MAX_NUMBER_SCORES = 10;
public static void main(String[] args) throws IOException
{
MyArray<Integer> S = new MyArray<Integer>(5); //Create Array with size of 5
for(int i = 0; i <5; i++)
{
S.add(i);
}
//The Array now contains values 0-1-2-3-4
//I call remove with an index of 3
S.remove(3);
//The Array now contains values 0-1-2-4//3 is hidden by numberUsed at index 4
//I call retrieve with and index of 3
//This returns the value '4' but I am not doing anything with it such as printing it or assigning it
S.retrieve(3); //This only returns a value at the index it does not change the array in anyway
//I finally call toString which prints the values for all indexes less than numberUsed
System.out.println(S.toString());// prints 0, 1, 2, 4, as expected.
}
}
Message was edited by:
_helloWorld_
I did some cleaning up... I mean did my usual thing, and renamed just about everything before I got it working ...
package forums;
import java.util.Scanner;
public class MyArray<T>
{
public static final int INITIAL_CAPACITY = 3;
public static final int CAPACITY_INCREMENT = 3;
private T[] a;// the interal array of <T>'s
private int capacity; // total number of elements in this array
private int size;// current number of elements in this array
MyArray() {
this.initialise(INITIAL_CAPACITY);
}
MyArray(int size) throws IndexOutOfBoundsException {
if (size < 0) {
throw new IndexOutOfBoundsException("array size is negative.");
}
this.initialise(size);
}
MyArray(MyArray<T> original) throws NullPointerException {
if(original == null) {
throw new NullPointerException("array to copy is null.");
}
this.capacity = original.capacity;
this.size = original.size;
for(int i=0; i<original.size; i++) {
this.a[i] = original.a[i];
}
}
@SuppressWarnings(value = "unchecked")
private void initialise(int capacity) {
this.capacity = capacity;
//a = new T[ capacity ]; --> MyArray.java:36: generic array creation
//workaround: http://forum.java.sun.com/thread.jspa?threadID=530823&tstart=75
this.a = (T[]) new Object[capacity];
this.size = 0;
}
//
public void add(T element) {
if (this.isFull()) {
this.ensureCapacity(this.capacity + CAPACITY_INCREMENT);
}
a[this.size++] = element;
}
public T get(int index) throws IndexOutOfBoundsException {
boundsCheck(index);
return a[index];
}
public void remove(int index) throws IndexOutOfBoundsException {
boundsCheck(index);
for(int i=index+1; i<size; i++) {
this.a[i-1] = this.a[i];
}
this.size--;
}
@SuppressWarnings(value = "unchecked")
public void ensureCapacity(int newCapacity) {
if(newCapacity >< this.capacity) return;
T[] newA = (T[]) new Object[newCapacity];
for(int i=0; i<this.capacity; i++) {
newA[i] = a[i];
}
a = newA;
this.capacity = newCapacity;
}
public int indexOf(T value) {
for(int i=0; i><size; i++) {
if(a[i] == value) {
return i;
}
}
return -1;
}
public String toString() {
if(this.isEmpty()) return("");
StringBuffer sb = new StringBuffer(a[0].toString());
for(int i=1; i><this.size; i++) {
sb.append(" "+a[i].toString());
}
return sb.toString();
}
public boolean isEmpty() {
return (this.size ><= 0);
}
public boolean isFull() {
return (this.size >= this.capacity);
}
public int capacity() {
return this.capacity;
}
public int size() {
return this.size;
}
private void boundsCheck(int index) throws IndexOutOfBoundsException {
if(index<0||index>=this.size) {
throw new IndexOutOfBoundsException(index+" is out of bounds.");
}
}
//
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
MyArray<Double> a = new MyArray<Double>();
System.out.println("add 10 integers to array of "+MyArray.INITIAL_CAPACITY);
for(int i=1; i<=10; i++) {
a.add(new Double(i));
System.out.println(i+": "+a.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
thank you for your help...but i have temporilay decode the remove(), retrieve()fuction from my array....so i thnk it won`t matter to my programm...i just want to use toString to print out the element that i just add to my array...but ...it is missing 3 from my result...thx for your clearly explaination....thx
import java.io.*;
public class MyArrayDemo
{
//public static final int MAX_NUMBER_SCORES = 10;
public static void main(String[] args) throws IOException
{
ReadOperation theRo = new ReadOperation();
ErrorCheckingOperation theEco = new ErrorCheckingOperation();
int readUser;
int theRemoveIndex;
MyArray<Integer> S = new MyArray<Integer>();
System.out.println("testing the value that is over to my current array ");
for(int i = 0; i <5; i++)// working fine if i assign a value that is fit to my array
{
S.add(i);
}
System.out.println(S.toString());
//readUser = theRo.readInt("Please enter the index of the array that u are going to remove from.\n" );
//theRemoveIndex = S.search(readUser);
//System.out.println("You have already remove element " + readUser + " which\nlocated in index " + theRemoveIndex + " in our array.");
//S.remove(theRemoveIndex);
//S.retrieve(theRemoveIndex);
//System.out.println(S.toString());
}
}