Sau khi thực hiện đoạn mã sau thì ArrayList chứa những phần tử nào? int x = 1; Integer y = 3; ArrayList a = new ArrayList(); a.add(3); a.add(9); a.add(5); a.remove(x); a.remove(y);
Question
Sau khi thực hiện đoạn mã sau thì ArrayList chứa những phần tử nào? int x = 1; Integer y = 3; ArrayList a = new ArrayList(); a.add(3); a.add(9); a.add(5); a.remove(x); a.remove(y);
Solution
Sau khi thực hiện đoạn mã trên, ArrayList sẽ chứa các phần tử như sau:
-
Đầu tiên, ta khởi tạo ArrayList a và thêm vào đó các phần tử 3, 9, 5. Vậy lúc này, ArrayList a sẽ chứa các phần tử: [3, 9, 5].
-
Tiếp theo, ta thực hiện lệnh a.remove(x);. Trong đó, x = 1. Lưu ý rằng, phương thức remove(int index) của ArrayList sẽ xóa phần tử tại vị trí index. Vì vậy, lệnh này sẽ xóa phần tử tại vị trí 1 (tức là phần tử 9). Sau lệnh này, ArrayList a sẽ chứa các phần tử: [3, 5].
-
Cuối cùng, ta thực hiện lệnh a.remove(y);. Trong đó, y = 3. Tuy nhiên, phương thức remove(Object o) của ArrayList sẽ xóa phần tử đầu tiên trong danh sách mà bằng với o. Vì vậy, lệnh này sẽ xóa phần tử 3. Sau lệnh này, ArrayList a sẽ chứa các phần tử: [5].
Vậy, sau khi thực hiện đoạn mã trên, ArrayList a sẽ chứa một phần tử duy nhất là 5.
Similar Questions
Phương thức nào sau đây cho phép chèn thêm một phần tử vào một vị trí của ArrayList? void add(int index, Object elem) Object remove(int index) boolean remove(Object) boolean add(Object)
What is the output of the following code snippet?ArrayList<Integer> numbers = new ArrayList<>();numbers.add(1);numbers.add(2);numbers.remove(1);System.out.println(numbers.size());Question 20Answera.0b.1c.2d.Error
关于数组或ArrayList的长度,以下哪个陈述是不正确的?对于ArrayList,可以通过一个ArrayList方法的返回值来获得对于Java数组,可以通过一个Java数组方法的返回值来获得对于Java数组和ArrayList,数组的最高索引等于数组中的元素数量减去1ArrayList的长度在声明后可以被更改Java数组的长度在声明后无法更改如果您认为上述所有陈述都是正确的,请选择此选项。
What is the output of the following program:import java.util.ArrayList;class Main { public static void main(String[] args){ ArrayList<String> animals = new ArrayList<>(); animals.add("Dog"); animals.add("Cat"); animals.add("Horse"); animals.remove(2); System.out.println("ArrayList: " + animals); }}Select one:a.ArrayList: [Dog, Cat]b.ArrayList: [Horse]c.ArrayList: [Dog, Cat, Horse]d.ArrayList: [Dog]
What is the output of the following code?import java.util.*;public class Main { public static void main(String[] args) { List list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); Iterator iterator = list.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); if (value == 2) { iterator.remove(); } } System.out.println(list); }}a)[2, 3]b)[3, 2, 1]c)[1, 2, 3]d)[1, 3]
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.