Android中ArrayList<E>动态数组用法

来源:互联网 发布:淘宝鹊桥怎么玩 编辑:程序博客网 时间:2024/05/21 10:48

     在Android SDK API中是这样描述ArrayList<E>这个类的,如下:

     ArrayList is an implementation of List, backed by an array. All optional operations including adding, removing, and replacing elements are supported.All elements are permitted, including null.

     This class is a good choice as your default List implementation.Vector synchronizes all operations, but not necessarily in a way that's meaningful to your application: synchronizing each call toget, for example, is not equivalent to synchronizing the list and iterating over it (which is probably what you intended).CopyOnWriteArrayList is intended for the special case of very high concurrency, frequent traversals, and very rare mutations.

     下面来看看其中一些常用方法:

      1、<T> T[] toArray(T[] contents)

      当声明了一个ArrayList<E>动态数组后,并添加了自己需要的数据后,想把这样的一个ArrayList<E>数组转换为普通的数组,如Integer[] TestArray = new Integer[100],这时可以采用以下方法,如下实例:

public class TestActivity extends Activity {
 
    ArrayList<Byte> arrayList;
    Byte[] testArray;
    Byte[] testArray1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
       
        arrayList = new ArrayList<Byte>();
        testArray = new Byte[100];
        
        testArray[0] = 0x01;
        testArray[1] = 0x02;
        testArray[2] = 0x03;
        
        arrayList.add(testArray[0]);
        arrayList.add(testArray[1]);
        arrayList.add(testArray[2]);


        testArray1 = new Byte[arrayList.size()]; //最终转换成的目标普通数组     
        arrayList.toArray(testArray1);//转换为普通数组,这样就可以用普通数组下标形式访问元素了
         
        System.out.println("arrayList.get(0)="+arrayList.get(0));
        if(testArray1[0].byteValue() == 0x01)
            System.out.println("arrayList.get(0)="+testArray1[2]);                         
    }
   
}
。。。。待续。。。。

原创粉丝点击