2 回答
TA贡献1780条经验 获得超5个赞
ArrayList实现List,因此您可以将其用作参数,例如
public void testMethod(List<String> list){
//....rest of your code goes here
}
始终记住,对象是通过引用传递的,因此您在此处的列表中所做的任何修改都将反映在调用该方法的方法中的列表中。
另外,对于您的代码,java 支持菱形运算符,即您不需要在 的右侧指定泛型类型=。左边,即为了可维护性,参考变量应该是父接口,例如
List<String> list = new ArrayList<>();
TA贡献1810条经验 获得超4个赞
you just need something like below
import java.util.ArrayList;
public class ReverseArrayList{
public static void main(String[] args) {
// Note: I used a sample array with 6 elements.
// I explain the code as if I am strictly using 6 elements
// However this may be done with any # of elements
ArrayList<String> reverseMe = new ArrayList<String>();
reverseMe.add("I");
reverseMe.add("am");
reverseMe.add("going");
reverseMe.add("to");
reverseMe.add("be");
reverseMe.add("reversed");
reverseList(reverseMe);
}
private static void reverseList(ArrayList<String> arrayList){
// This loop will run until we reach the midpoint of the array. At the midpoint, all the elements would be reversed
for (int i = 0; i < reverseMe.size()/2; i++){
// Save the first three values for later use.
String initial = reverseMe.get(i);
// The 1st element will be assigned to the last element, upto the midpoint
reverseMe.set(i, reverseMe.get(reverseMe.size() - i - 1));
// The last element will be assigned to the 1st element, upto the midpoint
reverseMe.set(reverseMe.size() - i - 1, initial);
}
// Displays the contents of the arraylist
for(String i: reverseMe){
System.out.println(i);
}
}
}
添加回答
举报