954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

ArrayList help

I had to make a arrayList and i do not know why is it not working

public class ArrayList<E> {

	private E[] theArray;
	private int size;
	private int capacity;


	public ArrayList(int initialCapacity) {
		this.size = 10;
		this.capacity = initialCapacity;
		theArray = (E[]) new Object[initialCapacity];
		
		
	}

	public ArrayList() {
		this(1024);
	}

	public E get(int index) throws Exception {
		
		if(index > size) {
			throw new Exception("the index is out of bounds");
		}else{
			return theArray[index];
		}
	}

	public void set(int index, E e) {
		E old = theArray[index];
		theArray[index] = e;
		
	}

	public void add(int index, E e) {
		if (size != theArray.length){
			E[] newArray = (E[])(new Object[size *2]);
			System.arraycopy(theArray, 0, newArray, 0, size);
			theArray = newArray;
		}
		for ( int i = size - 1; i <= index ; i--){
			theArray[i +1] = theArray[i];
			theArray[index] = e;
			size++;
		}
	}

	public void remove(int index) {
		for( int i = index; i < size - 1; i++){
				theArray[i] = theArray[i+1];
		}
		theArray[index] = null;
		size--;
	}

	public int getSize() {
		return this.size;
	}

	public boolean isEmpty() {
		return this.size == 0;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("[");
		for (int i = 0; i <size; i++) {
			sb.append(theArray[i]);
			if (i < size - 1)
				sb.append(", ");
		}
		return sb.toString() + "]";

	}

}

and this is the tester

public class MyTest3 {

	public static void main(String[] sa) {
		try {
			
			new MyTest3().tests();
		} catch (Exception ex) {
			System.err.println("*** Failure: " + ex.getMessage() + " ***");
		} finally {
			
		}
	}

	private void tests() throws Exception {
		

		
		ArrayList<String> als = new ArrayList<String>();
		als.add(0, "hello");
		
		System.out.println(als.get(0));

		
	}

}

I do not know what is wrong with this code please help me!

ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
 

Are you getting an error message? We can look at that then take it from there...

Dean_Grobler
Posting Whiz in Training
222 posts since Aug 2010
Reputation Points: 72
Solved Threads: 9
 

why do you have a size ánd a capacity? normally, this is one and the same value.

since you start of with the values:
size = 10
length = 1024

what exactly do you think this will do:

if (size != theArray.length){
			E[] newArray = (E[])(new Object[size *2]);
			System.arraycopy(theArray, 0, newArray, 0, size);
			theArray = newArray;
		}

?

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

that is making the array bigger if there are more elements than there are supposed too, like the ensureCapcity mehtod

ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
 

yes, but what is the logic behind it?
just work in your mind, or write it down, every step your actual running application is taking, and maybe you'll see what I mean.

but normally: the length(which is the size) and the capacity should always be the same, since the size defines the capacity of an array.

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

In a classic array list (eg java.util.ArrayList) you have a size which is the number of objects actually stored in the list at any time (initial value 0), and a capacity, which is the length of the private array that's used to hold the list (initial value is an arbitrary "big enough"). Capacity only increases when the array overflows (size > capacity) and you have to allocate a new bigger one.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

true, but here:

theArray = (E[]) new Object[initialCapacity];

when 1024 is passed as initialCapacity, both the actual size and capacity is 1024, or am I missing something here?

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

This is the OP's code, so he can do what he wants, but the "normal" implementation is that "size" refers to the current contents (number of added objects - number of removed objects). So initially the capacity is 1024 (length of the backing array), but the size is 0 (the array list contains zero objects). Add an object and the size becomes 1 and the capacity remains 1024. Add another 1023 objects and the size becomes 1024. Add yet one more object and the size becomes 1025, but internally the array will have been resized and the capacity will be some larger value, eg 2048.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

hmmm ...
I used to create a Generic array, and with each add test whether or not there were still elements at the end that are null. if so, I used the first null, else, if all elements taken, resizing the array with a value that could be set in the ArrayList class and copy over the values of the initial array to the resized one.
for each remove, I would just "trim" the array, to make sure that space was no longer occupied.

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

Your algorithm for add seems equivalent to just maintaining a size, unless the definition of your implementation allows null values to be added (like java.util.ArrayList does).
The algorithm for remove is valid, but could be really expensive if you have to create a new array and copy all the contents every time. Much slicker to null out the extra element ( or size-- )

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

mm ... the app I was working on needed an implementation which didn't take null values. but I see your point, if it should, testing whether the last element(s) is(are) null wouldn't tell me whether they were assigned or not.

at remove, I wasn't creating a new Array. I passed either the object or the index to be removed, (if object, searched the index) and the
for ( int i = index; i < length-1; i++)
array[i] = array[i+1];
and set the last element to null.
true, could be better when we're talking huge lists, but .. :)

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

OK, sorry, misunderstood what you initially said about remove. Nulling the last element after shifting down makes perfect sense if you don't allow null values.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

yeah well, a part of our assignment had to handle Objects in a List, and in the normal flow, a null wasn't possible. since I got tired of trying to explain my lab-partner what a NullPointerException was and how to handle it properly, I decided on a bit more of an idiot-proof (or Jan-proof, for that matter) implementation of the List, and hence, null marks the end :)

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 
public void add(int index, E e) {
		if (size > capacity){
			E[] newArray = (E[])(new Object[size *2]);
			System.arraycopy(theArray, 0, newArray, 0, size);
			theArray = newArray;
		}
		for ( int i = size; i <= index ; i++){
			theArray[i +1] = theArray[i];
			theArray[index] = e;
			size++;
		}
	}


it now works there was a problem with my add method

ilovejava
Junior Poster in Training
77 posts since Sep 2011
Reputation Points: 10
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: