简体   繁体   中英

How to write a remove method?

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
    }
}

You need to replace the following :

    for(int i = 0; i < size-1; i++) {
        index[i] = index[i+1];
    }

with:

    for(int i = index; i < size-1; i++) {
        data[i] = data[i+1];
    }
  • Start the loop with index
  • index[i] won't compile. Should be data[i] probably.

Note:
This will not delete the last element. You need to specifically check for it.

public class MyList<T> {

T[] items = (T[])new Object[10];

public int size() {
            
            int counter=0;
            for (int i = 0; i < items.length; i ++) {
                   
                if (items[i] != null) {
                     counter ++;
                }
                   
            }
            return counter;
          }

    public void remove(int t) {
            for (int i = t; i < items.length-1; i++) {
                
                items[i]=items[i+1];        
            }
            
            items[items.length-1]=null;
            
            items= Arrays.copyOf(items,size());     
                        
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM