Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a generic list?

public static <T> List<T> arrayListReverse(List<T> lst) {
  ArrayList reversed= new ArrayList();
  for (int i=lst.size()-1;i>=0;i--){
  <T> t= lst.get(i);
  reversed.add(t);
  }
 return reversed;
 }

I want to be be able to return a list that is a reversed version of the original list. It should be able to work for any type. I keep getting errors when it comes to the t=input.get(i); Edit: I would like to only use the List interface

like image 254
pythonbeginner4556 Avatar asked Aug 24 '26 05:08

pythonbeginner4556


2 Answers

public static <T> List<T> arrayListReverse(List<T> lst) {
    Collections.reverse(lst);
    return lst;
}
like image 148
Madushan Perera Avatar answered Aug 26 '26 23:08

Madushan Perera


<T> should be T:

public static <T> List<T> arrayListReverse(List<T> lst) {
    ArrayList reversed= new ArrayList();
    for (int i=lst.size()-1;i>=0;i--){
      T t = lst.get(i);
      reversed.add(t);
    }
   return reversed;
}
like image 26
Héctor Avatar answered Aug 26 '26 22:08

Héctor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!