ArrayList aList = new ArrayList();
//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(“你好世界”);这里只有一个字符串.但需要像“世界你好”这样的词来反转.
解决方法:
您可以将String拆分为一个String数组,将其转换为List< String>用Arrays.asList然后反转.就像是,
String str = "hello world";
List 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 al = Arrays.asList(str.split("\\s+"));
ListIterator listIterator = al.listIterator();
我明白了
Traversing ArrayList in forward directio using ListIterator
hello
world
Traversing ArrayList in reverse direction using ListIterator
world
hello
标签:java,arrays
来源: https://codeday.me/bug/20190623/1271044.html