ArrayList 反轉

Yake1965 2022-01-07 20:26:30 阅读数:525

arraylist

反轉 ArrayList

1、listIterator

ArrayList<Object> aList = new ArrayList<>();
//Add elements to ArrayList object
aList.add(1);
aList.add(2);
aList.add(3);
ListIterator it = aList.listIterator();
while (it.hasNext())
System.out.println("list: " + it.next());
while (it.hasPrevious())
System.out.println("reverse: " + it.previous());

2、Collections.reverse(aList);

Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);

3、遞歸

public ArrayList<Object> reverse(ArrayList<Object> list) {

if(list.size() > 1) {

Object value = list.remove(0);
reverse(list);
list.add(value);
}
return list;
}
// Or non-recursively: 
public ArrayList<Object> reverse(ArrayList<Object> list) {

for(int i = 0, j = list.size() - 1; i < j; i++) {

list.add(i, list.remove(j));
}
return list;
}
// A little more readable :
public static <T> ArrayList<T> reverse(ArrayList<T> list) {

int length = list.size();
ArrayList<T> result = new ArrayList<T>(length);
for (int i = length - 1; i >= 0; i--) {

result.add(list.get(i));
}
return result;
}

Solution without using extra ArrayList or combination of add() and remove() methods. 解决方案,無需使用額外的ArrayList或add()和remove()方法的組合。 Both can have negative impact if you have to reverse a huge list. 如果你必須撤銷一個巨大的列錶,兩者都會產生負面影響。

 public ArrayList<Object> reverse(ArrayList<Object> list) {

for (int i = 0; i < list.size() / 2; i++) {

Object temp = list.get(i);
list.set(i, list.get(list.size() - i - 1));
list.set(list.size() - i - 1, temp);
}
return list;
}

Another recursive solution 另一種遞歸解决方案

 public static String reverse(ArrayList<Float> list) {

if (list.size() == 1) {

return " " +list.get(0);
}
else {

return " "+ list.remove(list.size() - 1) + reverse(list);
}
}
版权声明:本文为[Yake1965]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201072026304803.html