在Java中,参数传递是通过值传递的。当你传递一个集合类型(如List、Set、Map等)时,实际上传递的是集合对象的引用。因此,你可以在方法内部修改集合的内容,但不能改变原始集合对象的引用。
以下是一个简单的示例,演示了如何在Java中传递集合类型的参数:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("A");
myList.add("B");
myList.add("C");
System.out.println("Before calling the method: " + myList);
modifyList(myList);
System.out.println("After calling the method: " + myList);
}
public static void modifyList(List<String> list) {
// 在方法内部修改集合内容
list.add("D");
list.remove(0);
}
}
输出结果:
Before calling the method: [A, B, C]
After calling the method: [B, C, D]
在这个例子中,我们创建了一个名为myList的ArrayList,并向其中添加了一些元素。然后我们调用了modifyList方法,并将myList作为参数传递。在modifyList方法内部,我们修改了集合的内容(添加了一个元素并删除了一个元素)。由于传递的是集合对象的引用,所以在方法调用后,原始集合myList的内容也发生了变化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。