Write a method called get which will return an element from the given index. Returns -1 if the index is out-of-bounds.
Write a method called remove which will remove an element from the given index. Returns -1 if the index is out-of-bounds. Data should be shifted accordingly during removal.
//This is the get method
public int get(int index){
if(index < 0 || index >= size) {
return -1;
}else {
return data[index];
}
}
//This is the remove method
public int remove(int index){
if(index < 0 || index >= size){
return -1;
}else {
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
}
}
This is as far as I got. Not sure how to proceed with the code. I'd appreciate if someone could guide me through. Thank you!
So far, you have the right idea. I am going to assume based on your syntax, that you are using an array. Your get()
method looks good, but you are missing some code from your remove()
method.
public int remove(int index){
//check for out-of-bounds
if(index < 0 || index >= size) //assumes size is set to the size of the array
{
return -1; }
else
{
for(int i = index; i < size-1; i++){
data[i] = data[i+1]; }
data[size-1] = 0; //assuming the array contains numbers, if not replace '0' with null
}
}