java数组知识总结(一)//按类

在线api

 目录:

零/数组(基本元素)

1.  声明一个数组 

2.  创建一个数组 

3.  数组名.length

4.  数组的引用

 

一/java.lang.reflect.Array     //基本就是没用!

  1.构造定长对象数组——newInstance(组建类型,维度)  //看了半天原来就是把以上两行缩成一行

  2.下标检索——get() //etc.

  3.下标设置——set() //etc.

 

二/java.util.Arrays  //定长数组工具类     

    aslist() 将数组转化成定长数组,数组中的元素包装成类

    binarySearch()

    copyOf()

    copyOfRange()

    equals()//数组判等

    fill()//全局赋值 局部赋值

    hashCode()

    sort()//局部排序 全局排序

    toString()

 

1.  从一个数组创建数组列表 //Arrays.asList()

2.  检查一个数组是否包含某个值(查找) //Arrays.asList().contains()

3.  输出一个数组 //Arrays.toString

4.  逆向一个数组 

5.  将一个数组转换为集(set) 

 

 
三/java.util.ArrayList<E>

1.构造

2.静态操作

  size()

  contains() get() indexOf() lastIndexOf()

  iterator() ListIterator()

3.动态操作 加减改

  add() addAll()

  remove() removeAll() removeRange()

  clear()

  set()

4.另一个串

  clone()//return Object

  subList()

  toArray()

 

*ArrayList的遍历

 

*调用toArray()

1.  将一个数组列表转换为数组 

 

四/其它

1.  连接两个数组 //   这个是Apache提供的class  org.apache.commons.lang.ArrayUtils

2.  把提供的数组元素放入一个字符串 //这个是Apache提供的class

3.  移除数组中的元素 //   这个是Apache提供的class  org.apache.commons.lang.ArrayUtils

4.  将整数转换为字节数组 

 


 

零/数组(基本元素)

1.  声明一个数组 

  People person[];

2.  创建一个数组 

  person= new People[4];

  对象数组分开创建 for(int i=0;i<4;I\i++) person[i]=new People();

  联立得:

    String[] aArray = new String[5];

    String[] bArray = {"a","b","c", "d", "e"};  

    String[] cArray = new String[]{"a","b","c","d","e"};   

3.  数组名.length

4.  数组的引用

 

Array

Arrays

Arraylist

 

一/java.lang.reflect.Array

 

//以下是正常构造对象数组的方式

  Animals [] an=new Animals[5];//声明

  for(int i=0;i<5;i++)  an[i]=new Animals();

 

  1.构造定长对象数组——newInstance(组建类型,维度)  //看了半天原来就是把以上两行缩成一行

//new可以构造一个对象

//newInstance 可以构造多个同类对象,即构造数组

  用指定的组件类型和维度创建一个新数组。如果成分类型表示一个非数组的类或接口,新的阵列具有dimensions.length尺寸和成分类型作为其组件类型。如果成分类型表示数组类,对新的数组的维数等于dimensions.length和尺寸componenttype数量总和。在这种情况下,新数组的组件类型为componentType组件类型。
新数组的维数的数目不一定要超过执行所支持的数组维度的数目(通常为255)。
  参数:
    成分类型:数组的组件类型的类对象
    维度:int代表新数组的维数的数组

  1)创建一个一维的、长度为10的、类型为Animals的数组:
      Animals[] an = (Animals[]) Array.newInstance(Animals, 10);

  2)创建一个二维的、3乘5的、类型为arraytest.MyClass的数组:
    int[] arrModel = new int[]{3,5};//建一个一维数组存待建数组的行和列,注意该一维数组仅有两个值
    Object arrObj = Array.newInstance(Animals, arrModel);

      //arrModel是一个一维数组,里面只有两个值,代表待建数组的行 列

      //用Object类指向构造的二维数组,当然你可以用一个数组的引用指向上面的二维数组,因为newInstance返回一个类

    

  使用的时候,我们也是可以利用Array类提供的方法来实现:

    System.out.println(Array.getLength(arrObj);//第一维长度为3
    System.out.println(Array.getLength(Array.get(arrObj, 2)));//第二维长度为5,这里如果写3,就会得到你意想之中的            

      java.lang.ArrayIndexOutOfBoundsException

    打印结果是如我所想的:
    3
    5

 

  2.下标检索——get() //etc.

  3.下标设置——set() //etc.

 

二/java.util.Arrays  //定长数组工具类

    aslist() 将数组转化成定长数组,数组中的元素包装成类

      方法asList返回的是new ArrayList<T>(a)。但是,这个ArrayList并不是java.util.ArrayList,它是一个Arrays类中的重新定义的内部类。 

 1 private static class ArrayList<E> extends AbstractList<E>
 2     implements RandomAccess, java.io.Serializable
 3     {
 4         private static final long serialVersionUID = -2764017481108945198L;
 5     private Object[] a;
 6     ArrayList(E[] array) {
 7             if (array==null)
 8                 throw new NullPointerException();
 9         a = array;
10     }
11     public int size() {
12         return a.length;
13     }
14     public Object[] toArray() {
15         return (Object[])a.clone();
16     }
17     public E get(int index) {
18         return (E)a[index];
19     }
20     public E set(int index, E element) {
21         Object oldValue = a[index];
22         a[index] = element;
23         return (E)oldValue;
24     }
25         public int indexOf(Object o) {
26             if (o==null) {
27                 for (int i=0; i<a.length; i++)
28                     if (a[i]==null)
29                         return i;
30             } else {
31                 for (int i=0; i<a.length; i++)
32                     if (o.equals(a[i]))
33                         return i;
34             }
35             return -1;
36         }
37         public boolean contains(Object o) {
38             return indexOf(o) != -1;
39         }
40     }
Arrays内部类arrayList源码

    可以通过asList构造ArrayList调用 size() get() set() indexOf() contains() 

      从这个内部类ArrayList的实现可以看出,它继承了类AbstractList<E>,但是没有重写add和remove方法,没有给出具体的实现。查看一下AbstractList类中对add和remove方法的定义,如果一个list不支持add和remove就会抛出UnsupportedOperationException。 

 1 public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
 2     /**
 3      * Sole constructor.  (For invocation by subclass constructors, typically
 4      * implicit.)
 5      */
 6     protected AbstractList() {
 7 }
 8 /**
 9      * Appends the specified element to the end of this List (optional
10      * operation). <p>
11      *
12      * This implementation calls <tt>add(size(), o)</tt>.<p>
13      *
14      * Note that this implementation throws an
15      * <tt>UnsupportedOperationException</tt> unless <tt>add(int, Object)</tt>
16      * is overridden.
17      *
18      * @param o element to be appended to this list.
19      * 
20      * @return <tt>true</tt> (as per the general contract of
21      * <tt>Collection.add</tt>).
22      * 
23      * @throws UnsupportedOperationException if the <tt>add</tt> method is not
24      *           supported by this Set.
25      * 
26      * @throws ClassCastException if the class of the specified element
27      *           prevents it from being added to this set.
28      * 
29      * @throws IllegalArgumentException some aspect of this element prevents
30      *            it from being added to this collection.
31      */
32     public boolean add(E o) {
33     add(size(), o);
34     return true;
35     }
36     /**
37      * Inserts the specified element at the specified position in this list
38      * (optional operation).  Shifts the element currently at that position
39      * (if any) and any subsequent elements to the right (adds one to their
40      * indices).<p>
41      *
42      * This implementation always throws an UnsupportedOperationException.
43      *
44      * @param index index at which the specified element is to be inserted.
45      * @param element element to be inserted.
46      * 
47      * @throws UnsupportedOperationException if the <tt>add</tt> method is not
48      *          supported by this list.
49      * @throws ClassCastException if the class of the specified element
50      *           prevents it from being added to this list.
51      * @throws IllegalArgumentException if some aspect of the specified
52      *          element prevents it from being added to this list.
53      * @throws IndexOutOfBoundsException index is out of range (<tt>index <
54      *          0 || index > size()</tt>).
55      */
56     public void add(int index, E element) {
57     throw new UnsupportedOperationException();
58     }
59     /**
60      * Removes the element at the specified position in this list (optional
61      * operation).  Shifts any subsequent elements to the left (subtracts one
62      * from their indices).  Returns the element that was removed from the
63      * list.<p>
64      *
65      * This implementation always throws an
66      * <tt>UnsupportedOperationException</tt>.
67      *
68      * @param index the index of the element to remove.
69      * @return the element previously at the specified position.
70      * 
71      * @throws UnsupportedOperationException if the <tt>remove</tt> method is
72      *          not supported by this list.
73      * @throws IndexOutOfBoundsException if the specified index is out of
74      *           range (<tt>index < 0 || index >= size()</tt>).
75      */
76     public E remove(int index) {
77     throw new UnsupportedOperationException();
78     }
79 }
AbstractList

      所以Arrays.asList产生的List是不可添加或者删除,否则就会产生UnsupportedOperationException。 

 

    binarySearch()  查找成功返回索引,否则返回负值

        //全局  static int binarySearch()(int[] a, int key)  

        //局部  static int binarySearch()(int[] a, int fromIndex, int toIndex, int key)

    copyOf()  返回数组

        //全局public static float[] copyOf(float/int/char/...[] original,int newLength)

    copyOfRange()  返回数组

        //局部 public static float[] copyOf(float/int/char/...[] original,int from,int to) 复制从索引from至索引 to-10(新数组长度to-from

    equals() //数组判等

    fill()//全局赋值 局部赋值

    hashCode()

    sort()  无返回值

        //全局排序  static void sort(int[] a)

        //局部排序  static void sort(int[] a, int fromIndex, int toIndex)

        //对对象数组按关键字排序(传入比较器)  sort(T[] a, Comparator<? super T> c)

        //                   sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

    toString()

 

    

    基本调用形式:

      int[] a={3,2,1};

       Arrays.sort(a);// 直接处理数组即可

 

1.  从一个数组创建数组列表 //Arrays.asList()

  1. String[] stringArray = { "a", "b", "c", "d", "e" };  
  2. ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));  
  3. System.out.println(arrayList);  
  4. // [a, b, c, d, e]  

 

2.  检查一个数组是否包含某个值(查找) //Arrays.asList().contains()

  1. String[] stringArray = { "a", "b", "c", "d", "e" };  
  2. boolean b = Arrays.asList(stringArray).contains("a");  
  3. System.out.println(b);  
  4. // true 

 

3.  输出一个数组 //Arrays.toString

  1. int[] intArray = { 1, 2, 3, 4, 5 };  
  2. String intArrayString = Arrays.toString(intArray);  
  3.    
  4. // print directly will print reference value  
  5. System.out.println(intArray);  
  6. // [I@7150bd4d  
  7.    
  8. System.out.println(intArrayString);//或者直接 System.out.println(Arrays.toString(intArray));
  9. // [1, 2, 3, 4, 5]  

 

4.  逆向一个数组 

  1. int[] intArray = { 1, 2, 3, 4, 5 };  
  2. ArrayUtils.reverse(intArray);  
  3. System.out.println(Arrays.toString(intArray));  
  4. //[5, 4, 3, 2, 1]  

 

5.  将一个数组转换为集(set) 

  1. Set<String> set = new HashSet<String>(Arrays.asList(stringArray));  
  2. System.out.println(set);  
  3. //[d, e, b, c, a]  
 
三/java.util.ArrayList<E>
 
详解  http://www.jb51.net/article/42764.htm

 可自动扩容的增强版的Array

package java.util;
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    // 序列版本号
    private static final long serialVersionUID = 8683452581122892189L;
    // 保存ArrayList中数据的数组
    private transient Object[] elementData;
    // ArrayList中实际数据的数量
    private int size;
    // ArrayList带容量大小的构造函数。
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        // 新建一个数组
        this.elementData = new Object[initialCapacity];
    }
    // ArrayList构造函数。默认容量是10。
    public ArrayList() {
        this(10);
    }
    // 创建一个包含collection的ArrayList
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    // 将当前容量值设为 =实际元素个数
    public void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
    // 确定ArrarList的容量。
    // 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”
    public void ensureCapacity(int minCapacity) {
        // 将“修改统计数”+1
        modCount++;
        int oldCapacity = elementData.length;
        // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }
    // 添加元素e
    public boolean add(E e) {
        // 确定ArrayList的容量大小
        ensureCapacity(size + 1);  // Increments modCount!!
        // 添加e到ArrayList中
        elementData[size++] = e;
        return true;
    }
    // 返回ArrayList的实际大小
    public int size() {
        return size;
    }
    // 返回ArrayList是否包含Object(o)
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    // 返回ArrayList是否为空
    public boolean isEmpty() {
        return size == 0;
    }
    // 正向查找,返回元素的索引值
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
            } else {
                for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
            }
            return -1;
        }
        // 反向查找,返回元素的索引值
        public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
            if (elementData[i]==null)
                return i;
        } else {
            for (int i = size-1; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i;
        }
        return -1;
    }
    // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
            if (elementData[i]==null)
                return i;
        } else {
            for (int i = size-1; i >= 0; i--)
            if (o.equals(elementData[i]))
                return i;
        }
        return -1;
    }

    // 返回ArrayList的Object数组
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    // 返回ArrayList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
    public <T> T[] toArray(T[] a) {
        // 若数组a的大小 < ArrayList的元素个数;
        // 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        // 若数组a的大小 >= ArrayList的元素个数;
        // 则将ArrayList的全部元素都拷贝到数组a中。
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    // 获取index位置的元素值
    public E get(int index) {
        RangeCheck(index);
        return (E) elementData[index];
    }
    // 设置index位置的值为element
    public E set(int index, E element) {
        RangeCheck(index);
        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }
    // 将e添加到ArrayList中
    public boolean add(E e) {
        ensureCapacity(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // 将e添加到ArrayList的指定位置
    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(
            "Index: "+index+", Size: "+size);
        ensureCapacity(size+1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
        elementData[index] = element;
        size++;
    }
    // 删除ArrayList指定位置的元素
    public E remove(int index) {
        RangeCheck(index);
        modCount++;
        E oldValue = (E) elementData[index];
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                 numMoved);
        elementData[--size] = null; // Let gc do its work
        return oldValue;
    }
    // 删除ArrayList的指定元素
    public boolean remove(Object o) {
        if (o == null) {
                for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
        } else {
            for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
        }
        return false;
    }
    // 快速删除第index个元素
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        // 从"index+1"开始,用后面的元素替换前面的元素。
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 将最后一个元素设为null
        elementData[--size] = null; // Let gc do its work
    }
    // 删除元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
            return true;
            }
        } else {
            // 便利ArrayList,找到“元素o”,则删除,并返回true。
            for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
            return true;
            }
        }
        return false;
    }
    // 清空ArrayList,将全部的元素设为null
    public void clear() {
        modCount++;
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }
    // 将集合c追加到ArrayList中
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacity(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
    // 从index位置开始,将集合c添加到ArrayList
    public boolean addAll(int index, Collection<? extends E> c) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(
            "Index: " + index + ", Size: " + size);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacity(size + numNew);  // Increments modCount
        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                 numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
    // 删除fromIndex到toIndex之间的全部元素。
    protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
    // Let gc do its work
    int newSize = size - (toIndex-fromIndex);
    while (size != newSize)
        elementData[--size] = null;
    }
    private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
    }
    // 克隆函数
    public Object clone() {
        try {
            ArrayList<E> v = (ArrayList<E>) super.clone();
            // 将当前ArrayList的全部元素拷贝到v中
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError();
        }
    }
    // java.io.Serializable的写入函数
    // 将ArrayList的“容量,所有的元素值”都写入到输出流中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();
        // 写入“数组的容量”
        s.writeInt(elementData.length);
    // 写入“数组的每一个元素”
    for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);
    if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }
    // java.io.Serializable的读取函数:根据写入方式读出
    // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in size, and any hidden stuff
        s.defaultReadObject();
        // 从输入流中读取ArrayList的“容量”
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];
        // 从输入流中将“所有的元素值”读出
        for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}
ArrayList源码

 

 

1.构造

  // 默认构造函数
  ArrayList()
  // capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。
  ArrayList(int capacity)
  // 创建一个包含collection的ArrayList
  ArrayList(Collection<? extends E> collection)  

 

2.静态操作

  size()

  contains() get() indexOf() lastIndexOf()

  iterator() ListIterator()

3.动态操作 加减改

  add() addAll()

  remove() removeAll() removeRange()

  clear()

  set()

4.另一个串

  clone()//return Object

  subList()

  toArray()

 

*ArrayList的遍历

ArrayList支持3种遍历方式
(01) 第一种,通过迭代器遍历。即通过Iterator去遍历。

Integer value = null;
Iterator iter = list.iterator();
while ( iter.hasNext()) {
    value = (Integer)iter.next();
}


(02) 第二种,随机访问,通过索引值去遍历。
由于ArrayList实现了RandomAccess接口,它支持通过索引值去随机访问元素。

Integer value = null;
int size = list.size();
for ( int i=0; i<size; i++) {
    value = (Integer)list.get(i);        
}


(03) 第三种,for循环遍历。如下:

Integer value = null;
for ( Integer integ:list) {
    value = integ;
}
 
 
*调用toArray()

当我们调用ArrayList中的 toArray(),可能遇到过抛出“java.lang.ClassCastException”异常的情况。下面我们说说这是怎么回事。
ArrayList提供了2个toArray()函数:
Object[] toArray()
<T> T[] toArray(T[] contents)
调用 toArray() 函数会抛出“java.lang.ClassCastException”异常,但是调用 toArray(T[] contents) 能正常返回 T[]。
toArray() 会抛出异常是因为 toArray() 返回的是 Object[] 数组,将 Object[] 转换为其它类型(如如,将Object[]转换为的Integer[])则会抛出“java.lang.ClassCastException”异常,因为Java不支持向下转型。具体的可以参考前面ArrayList.java的源码介绍部分的toArray()。
解决该问题的办法是调用 <T> T[] toArray(T[] contents) , 而不是 Object[] toArray()。
调用 toArray(T[] contents) 返回T[]的可以通过以下几种方式实现。

 

// toArray(T[] contents)调用方式一
public static Integer[] vectorToArray1(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    v.toArray(newText);
    return newText;
}
// toArray(T[] contents)调用方式二。最常用!
public static Integer[] vectorToArray2(ArrayList<Integer> v) {
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);
    return newText;
}
// toArray(T[] contents)调用方式三
public static Integer[] vectorToArray3(ArrayList<Integer> v) {
    Integer[] newText = new Integer[v.size()];
    Integer[] newStrings = (Integer[])v.toArray(newText);
    return newStrings;
}


1.  将一个数组列表转换为数组 

 
    1. String[] stringArray = { "a", "b", "c", "d", "e" };  
    2. ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));  
    3. String[] stringArr = new String[arrayList.size()];  
    4. arrayList.toArray(stringArr);  
    5. for (String s : stringArr)  
    6.     System.out.println(s);  

 

*ArrayList 示例

 1 import java.util.*;
 2 
 3 public class ArrayListTest {
 4     public static void main(String[] args) {
 5 
 6         // 创建ArrayList
 7         ArrayList list = new ArrayList();
 8         // 将“”
 9         list.add("1");
10         list.add("2");
11         list.add("3");
12         list.add("4");
13         // 将下面的元素添加到第1个位置
14         list.add(0, "5");
15         // 获取第1个元素
16         System.out.println("the first element is: "+ list.get(0));
17         // 删除“3”
18         list.remove("3");
19         // 获取ArrayList的大小
20         System.out.println("Arraylist size=: "+ list.size());
21         // 判断list中是否包含"3"
22         System.out.println("ArrayList contains 3 is: "+ list.contains(3));
23         // 设置第2个元素为10
24         list.set(1, "10");
25         // 通过Iterator遍历ArrayList
26         for(Iterator iter = list.iterator(); iter.hasNext(); ) {
27             System.out.println("next is: "+ iter.next());
28         }
29         // 将ArrayList转换为数组
30         String[] arr = (String[])list.toArray(new String[0]);
31         for (String str:arr)
32             System.out.println("str: "+ str);
33         // 清空ArrayList
34         list.clear();
35         // 判断ArrayList是否为空
36         System.out.println("ArrayList is empty: "+ list.isEmpty());
37     }
38 }
39 
40  

 

 

四/其它

1.  连接两个数组 //   这个是Apache提供的class  org.apache.commons.lang.ArrayUtils

  1. int[] intArray = { 1, 2, 3, 4, 5 };  
  2. int[] intArray2 = { 6, 7, 8, 9, 10 };  
  3. // Apache Commons Lang library  
  4. int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);  

 

2.  把提供的数组元素放入一个字符串 //这个是Apache提供的class

  1. // containing the provided list of elements  
  2. // Apache common lang  
  3. String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");  
  4. System.out.println(j);  
  5. // a, b, c  

3.  移除数组中的元素 //   这个是Apache提供的class  org.apache.commons.lang.ArrayUtils

  1. int[] intArray = { 1, 2, 3, 4, 5 };  
  2. int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array  
  3. System.out.println(Arrays.toString(removed));  



4.  将整数转换为字节数组 

    1. byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();  
    2.    
    3. for (byte t : bytes) {  
    4.    System.out.format("0x%x ", t);  
    5. }  

 


参考:

 

理解java数组 http://www.blogjava.net/flysky19/articles/92763.html?opt=admin
关于java数组的12个最好用的方法 http://www.iteye.com/news/28296

转载于:https://www.cnblogs.com/travelller-java/p/5007295.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值