为什么以下内容正确且有效?我认为每个对象都应该有不同的名称:
LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView);
int i = 0;
while (i<5) {
TextView wordView = new TextView(this);
wordView.setText(words.get(i));
rootView.addView(wordView);
i++;
}
但是,如果我尝试不使用循环:
TextView wordView = new TextView(this);
wordView.setText(words.get(0));
rootView.addView(wordView);
TextView wordView = new TextView(this);
wordView.setText(words.get(1));
rootView.addView(wordView);
这是不允许的,那么它在 java 中是如何工作的——一个循环创建具有相同名称的不同对象?
谢谢!
最佳答案
您需要了解的是局部变量的 block 作用域,即每个局部变量作用域都限制在 block 内并尝试以下代码,它会起作用:
{//1st block started
TextView wordView = new TextView(this);
wordView.setText(words.get(0));
rootView.addView(wordView);
//1st block wordView scope ends here
}//1st block ended
{//2nd block started
TextView wordView = new TextView(this);
wordView.setText(words.get(1));
rootView.addView(wordView);
//2nd block wordView scope ends here
}//2nd block ended
此外,进入 while
循环,您可以像上面那样将其视为 5 个 block (即,每个 block 在每次迭代中执行)。
可以引用here来自 JLS,局部变量作用域是如何工作的:
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.
此外,只需对您的短语“每个对象都应该有一个不同的名称”进行更正,这应该像“每个引用变量应该有一个不同的名称”这样更有意义(因为对象被分配给引用变量并由引用变量指向).
关于java - 使用循环具有相同名称的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441773/