25.1.27小记

ArrayList的操作

package notebook;
import java.util.ArrayList;

public class NoteBook {
    private ArrayList<String> notes = new ArrayList<String>();
    public void add(String s)
    {
      //在末尾增添元素
        notes.add(s);
    }
    public void add(String s,int location)
    {
         //指定位置上增添元素
        notes.add(location,s);
    }
    public int getSize()
    {
      //返回数组大小
        return notes.size();
    }
    public String getNote(int index)
    {
        //返回指定位置的内容
        return notes.get(index);
    }
    public void removeNote(int index)
    {
        //移除指定位置的内容
       notes.remove(index);
    }
    public String[] list()
    {
        String[] a = new String[notes.size()];
        notes.toArray(a);
        return a;
    }

    public static void main(String[] args) {

        NoteBook nb = new NoteBook();
        nb.add("first");
        nb.add("second");
        nb.add("third",1);
        System.out.println(nb.getSize());
        System.out.println(nb.getNote(0));
        System.out.println(nb.getNote(1));
        System.out.println(nb.getNote(2));
        nb.removeNote(1);
        String[] a = nb.list();
        for(String s : a){
            System.out.printf("%s ",s);
        }
    }
}


对象数组

其中每个元素都是对象的管理者而非对象本身
eg.

  //a[i]为对象的管理者
 String[] a = new String[10];

for-each循环

对于一般数组:

          int[] ia = new int[10];
            for(int k : ia)
            {
            //不起作用,因为每次的k实际上是对这个元素的复制品
                k++;
            }

对于对象数组 :

posted @ 2025-01-27 22:30  Ryan_jxy  阅读(19)  评论(0)    收藏  举报