How to remove the last string in an array element using parameters of another method named removeLast()

Viewed 62

Here is the question of exercise and my code:

Create the method public static void removeLast(ArrayList strings) in the exercise template. The method should remove the last value in the list it receives as a parameter. If the list is empty, the method does nothing.

public static void main(String[] args) {
    // Try your method in here
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("First");
    arrayList.add("Second");
    arrayList.add("Third");
    System.out.println(arrayList);
    removeLast(arrayList);
    System.out.println(arrayList);
}

public static void removeLast(ArrayList<String> strings) {
    strings.remove("Second");
    strings.remove("Third");
}

The sample output should look similar to the following:

[First, Second, Third]
[First]

What does the exercise mean by if the list is empty, the method does nothing?

I also keep getting error from local test saying the following:

removeLast method should remove the last element of the list.

Could someone help please?

3 Answers

"If the list is empty, the method does nothing" --> Check if the list is empty or not, if empty just return nothing , else delete last element(as per your requirement)

Example:

public static void removeLast(ArrayList<String> strings) {
        
        if( (strings.isEmpty())) {
         return;
        } 
        else {
            strings.remove(strings.size()-1);
            
        }
        
    
    }

you can first simply check list is empty of not if it is not empty than you can call size() methos it give last index number of list and simply you can call remove(int) method to remove last element.

 public static void removeLast(ArrayList<String> strings) {

   if(strings.isEmpty()) {

   } else {
      strings.remove(strings.size()-1);
   }
 }

There is no mathematical way to check if arrayList is empty or not. a. Either you have to check with method isEmpty() [or] b. check with array list size is greater than zero.

In application programming you have to check if array list is NOT NULL and the list is NOT EMPTY.

Related