boolean add(Object)
void add(Object, index)
Object remove(index)
int size()
class List:
//data members
int end//end element, zero-based
Object[] list//array
//constructors
List():
list = new Object[10] //default = 10
end = -1
List(int size):
list = new Object[size]
end = -1
//methods
boolean add(element):
//return false if element does not satisfy certain conditions
//increase array size if maxed out
if list.length() = end+1 :
//create new array and copy elements from current array
sizeNew = getNewSize() //determine the new size
listNew = new Object[sizeNew]
for i = 0 to end :
listNew[i] = list[i]
list = listNew
end++
list[end] = element
return true
void add(element, index):
if index > end :
throw exception('out of bounds')
//increase array size if maxed out
if list.length() = end+1 :
//create new array and copy elements from current array
sizeNew = getNewSize() //determine the new size
listNew = new Object[sizeNew]
for i = 0 to end :
listNew[i] = list[i]
list = listNew
//shift elements
for int i = end down to index :
list[i+1] = list[i]
end++
list[index] = element
Object remove(index):
if end < 0 :
throw exception('list empty')
if index > end :
throw exception('out of bounds')
removedObject = list[index]
//shift elements
for int i = index to end-1 :
list[i] = list[i+1]
list[end] = null
end--
return removedObject
int size():
return end+1
[Hat tip to TL]
what about multiple threads trying to add/delete/etc ...
ReplyDeleteThat would be just synchronizing parts of the code but the code should not change.
ReplyDelete