我正在尝试清空列表,这意味着删除所有项目。根据我的教授,我应该手动跟踪for循环。我知道随着每个项目的删除,大小都会变化,但是我不知道这与问题之间的关系。顺便说一句,正如您在下面的代码中看到的那样,它们都位于与MainActivity分开的活动中。这是我正在处理的代码:
public void removeAll(View view)
{
//Declare the reference
StringList the_list;
int i;
//Access the singleton list class
the_list = StringList.getInstance();
//Try to remove all items in the list
try
{
//Look through the list to remove each item
for(i = 0; i <= the_list.size(); i++)
{
the_list.remove(i);
}
Toast.makeText(RemoveAllActivity.this, "All items are removed successfully!",
Toast.LENGTH_SHORT).show();
}
catch(IndexOutOfBoundsException e)
{
Toast.makeText(RemoveAllActivity.this, "Error: Removing all items have failed!",
Toast.LENGTH_SHORT).show();
}
}
如果您想知道MainActivity的外观,我将展示我正在使用的功能:
public class MainActivity extends Activity {
public static TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringList the_list;
// set the reference to the "main" textview object so
// we do not have to retrieve it in every method below
tv = (TextView) findViewById(R.id.text_main);
// create/access the list of strings
the_list = StringList.getInstance();
// put some strings on the list (if the list is empty). Note that the
// "new" list might not be empty due to a restart of the app
if(the_list.isEmpty())
{
the_list.add(the_list.size(), "pizza");
the_list.add(the_list.size(), "crackers");
the_list.add(the_list.size(), "peanut butter");
the_list.add(the_list.size(), "jelly");
the_list.add(the_list.size(), "bread");
}
} // end onCreate
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*Some code*/
public void onOption6(MenuItem i)
{
// YYY: Remove all items from the list
startActivity(new Intent(this, RemoveAllActivity.class));
tv.setText("Removing all items from the list.");
} // end onOption6
如果您想知道单例列表类是什么样的:
public final class StringList extends LinkedList<String>
{
private static StringList instance = null;
private StringList()
{
// Exists only to defeat additional instantiations.
}
public static StringList getInstance()
{
if(instance == null)
instance = new StringList();
return instance;
}
} // end StringList
最佳答案
您按列表中的索引删除,然后在每个步骤重新评估size
,最后不删除列表的后半部分...
由于列表是Linkedlist
,因此可以删除列表的开头,直到没有其他元素为止:
while (the_list.isEmpty()) {
the_list.remove();
}
甚至更简单,请使用
clear()
方法:the_list.clear();
但是,如果您确实想遍历所有元素并使用大小,则可以从最后一个元素开始,但这可能不是很有效,因为您将在每个循环中遍历列表-通过索引访问最后一个元素:
for(int i = the_list.size() -1; i >= 0; i--) {
the_list.remove(i);
}