简体   繁体   中英

Deletes all but the last element from a given list in java collections

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.

Pseudo code:

while (list.length() > 1)
{
    list.removeElementAt(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;
}

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