【发布时间】:2019-10-09 07:42:33
【问题描述】:
基本上我想为我在 public static void main 中创建的“方法”创建一个单独的方法。
在这种方法中,我操作了一个数组列表,但不确定如何将数组列表用作函数中的参数
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");
// 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);
}
}
}
我研究了语法,但找不到任何显示语法的好视频。
【问题讨论】:
-
它与使用任何其他数据类型完全相同。你在说什么?
-
将数组列表作为方法参数传递的语法与将任何其他类型作为参数传递的语法相同。你尝试了什么,遇到了什么困难?
-
了解可变参数。如果您不知道需要多少参数,这是一个不错的选择
-
例如,如果你想使用一个数组作为参数,你会这样做:int x[] 作为参数,那么arraylists呢?