Java 实例化和初始化列表(需要解释)
Java instantiated and initialized list (Explanation needed)
谁能帮我理解为什么答案是 (B)?
private List<String> animals;
public void manipulate()
{
for (int k = animals.size() - 1; k > 0; k--)
{
if (animals.get(k).substring(0, 1).equals("b"))
{
animals.add(animals.size() - k, animals.remove(k));
}
}
}
假设动物已经被实例化并初始化为以下内容。
[“熊”、“斑马”、“鲈鱼”、“猫”、“考拉”、“狒狒”]
调用 manipulate 后动物的内容会是什么?
(A) ["baboon", "zebra", "bass", "cat", "bear", "koala"]
(B) ["bear", "zebra", "bass", "cat", "koala", "baboon"]
(C) ["baboon", "bear", "zebra", "bass", "cat", "koala"]
(D) ["bear", "baboon", "zebra", "bass", "cat", "koala"]
(E) ["zebra", "cat", "koala", "baboon", "bass", "bear"]
在第一次迭代中,
K=5
Baboon is added to index (6 - 5), you get (D)
第二次迭代,
K=4, element is cat
nothing happens.
第三次迭代,
K=3, element is bass
bass is added to index (6-3), gets added to its own index, remains (D)
第四次迭代,
K=2, element is zebra
nothing happens.
第五次迭代,
K=1, element is baboon
baboon is added to index (6-1) which is its original index, you get (B)
第六次迭代,
K=0. there is no iteration as condition k>0 is not fulfilled.
谁能帮我理解为什么答案是 (B)?
private List<String> animals;
public void manipulate()
{
for (int k = animals.size() - 1; k > 0; k--)
{
if (animals.get(k).substring(0, 1).equals("b"))
{
animals.add(animals.size() - k, animals.remove(k));
}
}
}
假设动物已经被实例化并初始化为以下内容。 [“熊”、“斑马”、“鲈鱼”、“猫”、“考拉”、“狒狒”] 调用 manipulate 后动物的内容会是什么?
(A) ["baboon", "zebra", "bass", "cat", "bear", "koala"]
(B) ["bear", "zebra", "bass", "cat", "koala", "baboon"]
(C) ["baboon", "bear", "zebra", "bass", "cat", "koala"]
(D) ["bear", "baboon", "zebra", "bass", "cat", "koala"]
(E) ["zebra", "cat", "koala", "baboon", "bass", "bear"]
在第一次迭代中,
K=5
Baboon is added to index (6 - 5), you get (D)
第二次迭代,
K=4, element is cat
nothing happens.
第三次迭代,
K=3, element is bass
bass is added to index (6-3), gets added to its own index, remains (D)
第四次迭代,
K=2, element is zebra
nothing happens.
第五次迭代,
K=1, element is baboon
baboon is added to index (6-1) which is its original index, you get (B)
第六次迭代,
K=0. there is no iteration as condition k>0 is not fulfilled.