-2

Implement a method below which deletes all but the last element from a given list.

import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   for (int k : list)
   {
      set.remove(0, -2);
   }
   return set;
}

I just started programming and this is a practice question and I was wondering if this type of solution would make sense. I started from the first array block(0) and it stops at the the array block before the last element(-2) and removes it, only keeping the last element and returning it at the end.

  • Why you need to delete all, just create a new list with the last element is enough – Dang Nguyen Mar 28 '19 at 03:37
  • Do take note that `.remove(...)` in a `for` loop is not correct. Please see: https://stackoverflow.com/questions/17279519/removing-items-from-a-list – KevinO Mar 28 '19 at 03:39
  • Also, you cannot return a value from a `void` method. Given that this question is probably homework, I'm assuming the point is to modify the `list` that was provided in the parameter, so creating a new `List` is likely incorrect. – KevinO Mar 28 '19 at 03:42

3 Answers3

0

Pseudo code:

while (list.length() > 1)
{
    list.removeElementAt(0);
}
John3136
  • 28,809
  • 4
  • 51
  • 69
0

Change the return type void to List<String>

public static List<String> allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   String last=set.remove(set.size() - 1);
   set.clear();
   set.add(last);
   return set;
}

Or

public static List<String> allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   set.subList(0, set.size() - 1).clear();
   return set;
}
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

Only create a new list with the last element

public static List<String> allButLast(List<String> list) {
    List<String> set = new ArrayList<String>();
    set.add(list.get(list.size()-1))
    return set;
}