ArrayList<String> aList = new ArrayList<String>();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
//Get an object of ListIterator using listIterator() method
ListIterator listIterator = aList.listIterator();
//Traverse in forward direction
System.out.println("Traversing ArrayList in forward directio using ListIterator");
while(listIterator.hasNext())
System.out.println(listIterator.next());
/*
Traverse the ArrayList in reverse direction using hasPrevious and previous
methods of ListIterator. hasPrevious method returns true if
ListIterator has more elements to traverse in reverse direction.
Previous method returns previous element in the list.
*/
System.out.println("Traversing ArrayList in reverse direction using ListIterator");
while(listIterator.hasPrevious())
System.out.println(listIterator.previous());
}
}
在上面的代码列表中,数组值反向打印。但是我需要使用相同的方法来反转单个数组句子。 例如:aList.add(“你好世界”);这里只有一个字符串。但需要像“世界问候”一样颠倒这个词。
答案 0 :(得分:4)
您可以split
String
成String
(s)数组,将其转换为List<String>
Arrays.asList
然后reverse
那个。像,
String str = "hello world";
List<String> al = Arrays.asList(str.split("\\s+"));
Collections.reverse(al);
for (String s : al) {
System.out.print(s + " ");
}
System.out.println();
输出(按要求)
world hello
或者,修改您的ListIterator
(不应使用raw types)。像,
String str = "hello world";
List<String> al = Arrays.asList(str.split("\\s+"));
ListIterator<String> listIterator = al.listIterator();
我得到了
Traversing ArrayList in forward directio using ListIterator
hello
world
Traversing ArrayList in reverse direction using ListIterator
world
hello