嗨,我是一个新手,刚刚学习 java。我在研究 ArrayList n 时遇到了这个代码,例如 {CODE1}。我想使用相同的代码,但添加一个 ArrayListDemo 构造函数并创建诸如 displayList 和 removeElement 之类的方法。我试图找到这样的例子,但我不明白。
这是我尝试的代码 {CODE2} 通过我的修改,请告诉我哪里出错了。
*** CODE1 {示例代码}** * *
import java.util.ArrayList;
public class AraryListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
System.out.print("Initial size of al : " + al.size());
System.out.print("\n");
//add.elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1,"A2");//inserts objects "A2" into array at index 1
System.out.print("size of al after additions " + al.size());
System.out.print("\n");
//display the array list
System.out.print("contents of al: " + al );
System.out.print("\n");
//Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.print("size of after deletions : " + al.size());
System.out.print("\n");
System.out.print("contents of al:" + al);
}
}
** * ** * **代码 2 {我的修改}** * ** * ** * ****
class ArrayListDemo
{
ArrayList<String> al;//variable declared
ArrayListDemo() throws IOException//try constructor for this
{
al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n Enter Student Names");
for(int i=0;i<=5;i++)// will dispaly
{
al.add(br.readLine());
}
}
void dispList(ArrayList <String> al)
{
System.out.println("\n Display Student Names");
for(String str : al)
{
System.out.println("\t Name : "+str+"\n");
}
}
}
class DisplayArrayList
{
public static void main(String []args) throws IOException
{
ArrayList <String> al = new ArrayList <String>();
ArrayListDemo e = new ArrayListDemo();
e.dispList(al);
}
}