简体   繁体   中英

Remove first item from Array in Javax

Got an assignment question which asks to return the first item from an array and then remove it. If the array is empty I should return null. Here is my code:

public String pop(){
    if(arrayLength == 0){
        return null;
    }else{
        String[] temp = new String[100];
        String firstItem = StringStack[0];
        for(int i = 1; i<StringStack.length; i++){
            temp[i] = StringStack[i];
        }
        StringStack = temp;
        return firstItem;
    }
}

The arrayLength variable is set by this method and works fine:

public int getLength(){
    int count = 0;
    for (String s : StringStack) {
        if (s != null) {
            count++;
        }
    }
    return count;
}

I cant figure out what it is I am doing wrong here. Another part of this question is I cant use any collections or Systems.arraycopy so I have to use for loops and other basic operators to solve this. It also has to be an array so I cant use array lists or other data structures.

here is version with two fixed problems:

public String pop() {
    if(StringStack == null || StringStack.length == 0)
        return null;

    String firstItem = StringStack[0];

    String[] temp = new String[StringStack.length-1]; // allocate proper size
    for(int i = 1; i<StringStack.length; i++){
        temp[i-1] = StringStack[i]; // i-1 for temp array
    }
    StringStack = temp;

    return firstItem;
}

Got an assignment question which asks to return the first item from an array and then remove it. If the array is empty I should return null. Here is my code:

public String pop(){
    if(arrayLength == 0){
        return null;
    }else{
        String[] temp = new String[100];
        String firstItem = StringStack[0];
        for(int i = 1; i<StringStack.length; i++){
            temp[i] = StringStack[i];
        }
        StringStack = temp;
        return firstItem;
    }
}

The arrayLength variable is set by this method and works fine:

public int getLength(){
    int count = 0;
    for (String s : StringStack) {
        if (s != null) {
            count++;
        }
    }
    return count;
}

I cant figure out what it is I am doing wrong here. Another part of this question is I cant use any collections or Systems.arraycopy so I have to use for loops and other basic operators to solve this. It also has to be an array so I cant use array lists or other data structures.

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