Java学习笔记-数组与ArrayList

一、数组

    1、声明

             type[] identifier=new type[length]

           Java创建数组时,将每个元素初始化为该类型的默认值。与C语言不同的是,Java数组可以动态改变大小

             例:int nJudges=readInt("enter number of judges:");

                   double[] scores=new double[nJudges];

          此外,数组的类型既可以是基本类型,也可以是用户自定义的类

二、ArrayList类

     1、声明

             要指定储存在ArrayList中值的类型,可以在尖括号中写类的名称,然后在ArrayList类出现的地方写它的名称

            如:ArrayList<String> stringList=new ArrayList<String>();构造了一个空的字符串ArrayList

     下面是一段代码表明ArrayList的用法:

            public class ReverseArrayList extends ConsoleProgram

            {

                  public void run()

                  {

                        println("This program reverses the elements in an ArrayList.");

                        println("Use "+SENTINEL+"to singal the end of the list");

                        ArrayList<Integer> list=readArrayList();

                        reverseArrayList(list);

                        printArrayList(list);

                    }

                   private ArrayList<Integer> readArrayList()

                   {

                       ArrayList<Integer> list=new ArrayList<Integer>();

                       while(true)

                       {

                           int value=readInt("?");

                           if(value==SENTINEL) break;

                           list.add(value);

                        }

                        return list;

                   }

                   private void printArrayList(ArrayList list)

                   {

                        for(int i=0;i<list.size();i++)

                        {

                              int value=(Integer)list.get(i);

                              println(value);

                          }

                   }

                   private void reverseArrayList(ArrayList list)

                   {

                         for(int i=0;i<list.size()/2;i++)

                              swapElements(list,i,list.size()-i-1);

                    }

                    private void swapElements(ArrayList list,int p1,int p2)

                    {

                         int temp=list.get(p1);

                         list.set(p1,list.get(p2));

                         list.set(p2,temp);

                     }

 }

 

三、LinkedList类

这个类和ArrayList都是实现了List接口的类,操作上有极大的类似。有一点不同的是:ArrayList在实现的时候是数组的结构,而LinkedList在实现的时候使用的是链表,所以当有频繁的插入和删除操作的时候,使用后者是个不错的选择。

posted @ 2010-02-04 15:53  明之道  阅读(3518)  评论(0编辑  收藏  举报