2 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
ArrayList實(shí)現(xiàn)List,因此您可以將其用作參數(shù),例如
public void testMethod(List<String> list){
//....rest of your code goes here
}
始終記住,對(duì)象是通過(guò)引用傳遞的,因此您在此處的列表中所做的任何修改都將反映在調(diào)用該方法的方法中的列表中。
另外,對(duì)于您的代碼,java 支持菱形運(yùn)算符,即您不需要在 的右側(cè)指定泛型類型=。左邊,即為了可維護(hù)性,參考變量應(yīng)該是父接口,例如
List<String> list = new ArrayList<>();

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
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);
}
}
}
添加回答
舉報(bào)