hey guys I need help to implement a array list I have the skeleton structure written out but some of the methods do not work and I have troubles with the remove method please help and how do you do isEmpy method

//tried my best dont get some stuff 
public class ArrayList{
	private Object[] array;
	private int position;
	ArrayList(){
		this.array = new Object[15];
		this.position = 0;
	}
	//apprently this does not work and my next add method works....strange
	public void add(Object o){

		array[this.position]= o;
		this.position++;
	}
	public void add(int index, Object o){
		if(index<=array.length){
			Object[] tempArray = null;
			tempArray = array;
			array = new Object[index + array.length*2];
			System.arraycopy(tempArray, 0, array, 0, tempArray.length);
			
		}
		array[index]=o;
	}
	public void clear(){
		for(int i=0;i<array.length;i++){
			array[i] = null;
		}
	}
	public boolean contains(Object o){
		for(int i = 0; i<array.length;i++)
			if(this.array[i] == o) return true;
		return false;
	}
	public Object get(int index){
		return this.array[index];
	}
	public int  indexOf(Object o){
		
		for(int i = 0; i<array.length; i++)
			if(this.array[i] == o) return i;
		return 0;
	}
	public boolean isEmpty(){
		return true;
	}
	public int lastIndexOf(Object o){
		for(int i = array.length - 1; i>=0;i--)
			if(array[i]==o) return i;
		return 0;
		
	}
	//????
	public boolean remove(Object o){
		return true;
	}
	public int size(){
		return array.length;
	}
	//???
	public boolean remove(int index){
		return true;
	}
	
	public Object set(int index, Object o){
		o = array[index];
		array[index] = o;
		return o;
		
	}


}

please help me on fixing my code thank you so much people

Recommended Answers

All 3 Replies

A couple of notes:

1. I see no problem with

public void add(Object o){
  array[this.position] = o;
  this.position++;
}

2. The if-statement in your second add() method is wrong

3. You should do some check on the index in several of the methods

4. indexOf()/lastIndexOf() shouldn't return 0 if object isn't found

5. isEmpty() is not implemented

6. The remove() methods should simply do what the clear() method does, but for one/multiple elements

7. size() method returns the length of the array, not the number of objects in the "ArrayList"

8. You are checking equality with "==", that will most likely cause problems

but the second add method works

but the second add method works

And you know this how? You tried to add one element and the program did not complain?
Check my previous points.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.