Jaki jest najprostszy sposób odwrócenia ArrayList?
Jaki jest najprostszy sposób odwrócenia tej ArrayList?
ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
while (aList.listIterator().hasPrevious())
Log.d("reverse", "" + aList.listIterator().previous());
10 answers
Collections.reverse(aList);
Example (Reference):
ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 13:53:17
Nie jest to najprostszy sposób, ale jeśli jesteś fanem rekurencji, możesz być zainteresowany następującą metodą odwrócenia tablicy:
public ArrayList<Object> reverse(ArrayList<Object> list) {
if(list.size() > 1) {
Object value = list.remove(0);
reverse(list);
list.add(value);
}
return list;
}
Lub non-rekurencyjnie:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-19 06:07:49
Sztuczka polega na zdefiniowaniu "odwrotności". Można modyfikować listę w miejscu, tworzyć kopię w odwrotnej kolejności lub tworzyć widok w odwróconej kolejności.
Najprostszym sposobem, intuicyjnie mówiąc , jest Collections.reverse
:
Collections.reverse(myList);
Ta metoda modyfikuje listę w miejscu. Oznacza to, że Collections.reverse
pobiera listę i nadpisuje jej elementy, nie pozostawiając po sobie niezauważonej kopii. Jest to odpowiednie dla niektórych przypadków użycia, ale nie dla innych; ponadto zakłada, że lista jest modyfikowalne. Jeśli to jest do przyjęcia, jesteśmy dobrzy.
Jeśli nie, można utworzyć kopię w odwrotnej kolejności :
static <T> List<T> reverse(final List<T> list) {
final List<T> result = new ArrayList<>(list);
Collections.reverse(result);
return result;
}
To podejście działa, ale wymaga dwukrotnego powtórzenia listy. Konstruktor kopiujący (new ArrayList<>(list)
) iteruje nad listą, podobnie jak Collections.reverse
. Możemy przepisać tę metodę tylko raz, jeśli jesteśmy tak skłonni:
static <T> List<T> reverse(final List<T> list) {
final int size = list.size();
final int last = size - 1;
// create a new list, with exactly enough initial capacity to hold the (reversed) list
final List<T> result = new ArrayList<>(size);
// iterate through the list in reverse order and append to the result
for (int i = last; i >= 0; --i) {
final T element = list.get(i);
result.add(element);
}
// result now holds a reversed copy of the original list
return result;
}
Jest to bardziej wydajne, ale także bardziej gadatliwe.
Alternatywnie, możemy przepisać powyższe, aby użyć Java 8 ' S stream
API, które niektórzy ludzie uważają za bardziej zwięzłe i czytelne niż powyższe:
static <T> List<T> reverse(final List<T> list) {
final int last = list.size() - 1;
return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
.map(i -> (last - i)) // reverse order
.mapToObj(list::get) // map each index to a list element
.collect(Collectors.toList()); // wrap them up in a list
}
Nb. to Collectors.toList()
daje bardzo niewiele gwarancji co do listy wyników. Jeśli chcesz mieć pewność, że wynik wróci jako ArrayList, użyj Collectors.toCollection(ArrayList::new)
.
Trzecią opcją jest utworzenie widoku w odwróconej kolejności . Jest to rozwiązanie bardziej skomplikowane i godne dalszej lektury/własnego pytania. Guawa ' s Lists # reverse method is a really starting punkt.
Wybór "najprostszej" implementacji jest pozostawiony jako ćwiczenie dla czytelnika.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-19 16:49:05
Rozwiązanie bez użycia dodatkowej ArrayList lub kombinacji metod add() I remove (). Oba mogą mieć negatywny wpływ, jeśli trzeba odwrócić ogromną 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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 09:50:48
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
myArray.add(3);
int reverseArrayCounter = myArray.size() - 1;
for (int i = reverseArrayCounter; i >= 0; i--) {
System.out.println(myArray.get(i));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-05 02:52:30
Odwrócenie tablicy w sposób rekurencyjny i bez tworzenia nowej Listy do dodawania elementów:
public class ListUtil {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
System.out.println("Reverse Order: " + reverse(arrayList));
}
public static <T> List<T> reverse(List<T> arrayList) {
return reverse(arrayList,0,arrayList.size()-1);
}
public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {
if(startIndex<lastIndex) {
T t=arrayList.get(lastIndex);
arrayList.set(lastIndex,arrayList.get(startIndex));
arrayList.set(startIndex,t);
startIndex++;
lastIndex--;
reverse(arrayList,startIndex,lastIndex);
}
return arrayList;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-10 09:54:48
Trochę bardziej czytelne:)
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-11 09:28:04
Inne rozwiązanie rekurencyjne
public static String reverse(ArrayList<Float> list) {
if (list.size() == 1) {
return " " +list.get(0);
}
else {
return " "+ list.remove(list.size() - 1) + reverse(list);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-06 23:57:57
Na wypadek, gdybyśmy używali Java 8, możemy użyć Stream. ArrayList jest listą dostępu losowego i możemy uzyskać strumień elementów w odwrotnej kolejności, a następnie zebrać go do nowego ArrayList
.
public static void main(String[] args) {
ArrayList<String> someDummyList = getDummyList();
System.out.println(someDummyList);
int size = someDummyList.size() - 1;
ArrayList<String> someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
System.out.println(someDummyListRev);
}
private static ArrayList<String> getDummyList() {
ArrayList dummyList = new ArrayList();
//Add elements to ArrayList object
dummyList.add("A");
dummyList.add("B");
dummyList.add("C");
dummyList.add("D");
return dummyList;
}
Powyższe podejście nie jest odpowiednie dla LinkedList, ponieważ nie jest to dostęp losowy. Możemy również użyć instanceof
do sprawdzenia.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-20 04:22:57
Możemy również zrobić to samo używając Javy 8.
public static<T> List<T> reverseList(List<T> list) {
List<T> reverse = new ArrayList<>(list.size());
list.stream()
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(reverse::add);
return reverse;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 09:58:49