目录:
零/数组(基本元素)
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)
1.构造
2.静态操作
size()
contains() get() indexOf() lastIndexOf()
iterator() ListIterator()
3.动态操作 加减改
add() addAll()
remove() removeAll() removeRange()
clear()
set()
4.另一个串
clone()//return Object
subList()
toArray()
*ArrayList的遍历
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类中的重新定义的内部类。
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private Object[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return (Object[])a.clone();
}
public E get(int index) {
return (E)a[index];
}
public E set(int index, E element) {
Object oldValue = a[index];
a[index] = element;
return (E)oldValue;
}
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
}
Arrays内部类arrayList源码
可以通过asList构造ArrayList调用 size() get() set() indexOf() contains()
从这个内部类ArrayList的实现可以看出,它继承了类AbstractList<E>,但是没有重写add和remove方法,没有给出具体的实现。查看一下AbstractList类中对add和remove方法的定义,如果一个list不支持add和remove就会抛出UnsupportedOperationException。
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
protected AbstractList() {
}
/**
* Appends the specified element to the end of this List (optional
* operation). <p>
*
* This implementation calls <tt>add(size(), o)</tt>.<p>
*
* Note that this implementation throws an
* <tt>UnsupportedOperationException</tt> unless <tt>add(int, Object)</tt>
* is overridden.
*
* @param o element to be appended to this list.
*
* @return <tt>true</tt> (as per the general contract of
* <tt>Collection.add</tt>).
*
* @throws UnsupportedOperationException if the <tt>add</tt> method is not
* supported by this Set.
*
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this set.
*
* @throws IllegalArgumentException some aspect of this element prevents
* it from being added to this collection.
*/
public boolean add(E o) {
add(size(), o);
return true;
}
/**
* Inserts the specified element at the specified position in this list
* (optional operation). Shifts the element currently at that position
* (if any) and any subsequent elements to the right (adds one to their
* indices).<p>
*
* This implementation always throws an UnsupportedOperationException.
*
* @param index index at which the specified element is to be inserted.
* @param element element to be inserted.
*
* @throws UnsupportedOperationException if the <tt>add</tt> method is not
* supported by this list.
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list.
* @throws IllegalArgumentException if some aspect of the specified
* element prevents it from being added to this list.
* @throws IndexOutOfBoundsException index is out of range (<tt>index <
* 0 || index > size()</tt>).
*/
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
/**
* Removes the element at the specified position in this list (optional
* operation). Shifts any subsequent elements to the left (subtracts one
* from their indices). Returns the element that was removed from the
* list.<p>
*
* This implementation always throws an
* <tt>UnsupportedOperationException</tt>.
*
* @param index the index of the element to remove.
* @return the element previously at the specified position.
*
* @throws UnsupportedOperationException if the <tt>remove</tt> method is
* not supported by this list.
* @throws IndexOutOfBoundsException if the specified index is out of
* range (<tt>index < 0 || index >= size()</tt>).
*/
public E remove(int index) {
throw new UnsupportedOperationException();
}
}
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()
- String[] stringArray = { "a", "b", "c", "d", "e" };
- ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
- System.out.println(arrayList);
- // [a, b, c, d, e]
2. 检查一个数组是否包含某个值(查找) //Arrays.asList().contains()
- String[] stringArray = { "a", "b", "c", "d", "e" };
- boolean b = Arrays.asList(stringArray).contains("a");
- System.out.println(b);
- // true
3. 输出一个数组 //Arrays.toString
- int[] intArray = { 1, 2, 3, 4, 5 };
- String intArrayString = Arrays.toString(intArray);
- // print directly will print reference value
- System.out.println(intArray);
- // [I@7150bd4d
- System.out.println(intArrayString);//或者直接 System.out.println(Arrays.toString(intArray));
- // [1, 2, 3, 4, 5]
4. 逆向一个数组
- int[] intArray = { 1, 2, 3, 4, 5 };
- ArrayUtils.reverse(intArray);
- System.out.println(Arrays.toString(intArray));
- //[5, 4, 3, 2, 1]
5. 将一个数组转换为集(set)
- Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
- System.out.println(set);
- //[d, e, b, c, a]
可自动扩容的增强版的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去遍历。
Iterator iter = list.iterator();
while (iter.hasNext()) {
value = (Integer)iter.next();
}
(02) 第二种,随机访问,通过索引值去遍历。
由于ArrayList实现了RandomAccess接口,它支持通过索引值去随机访问元素。
int size = list.size();
for (int i=0; i<size; i++) {
value = (Integer)list.get(i);
}
(03) 第三种,for循环遍历。如下:
for (Integer integ:list) {
value = integ;
}
当我们调用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. 将一个数组列表转换为数组
- String[] stringArray = { "a", "b", "c", "d", "e" };
- ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
- String[] stringArr = new String[arrayList.size()];
- arrayList.toArray(stringArr);
- for (String s : stringArr)
- System.out.println(s);
*ArrayList 示例
import java.util.*; public class ArrayListTest {
public static void main(String[] args) { // 创建ArrayList
ArrayList list = new ArrayList();
// 将“”
list.add("1");
list.add("2");
list.add("3");
list.add("4");
// 将下面的元素添加到第1个位置
list.add(0, "5");
// 获取第1个元素
System.out.println("the first element is: "+ list.get(0));
// 删除“3”
list.remove("3");
// 获取ArrayList的大小
System.out.println("Arraylist size=: "+ list.size());
// 判断list中是否包含"3"
System.out.println("ArrayList contains 3 is: "+ list.contains(3));
// 设置第2个元素为10
list.set(1, "10");
// 通过Iterator遍历ArrayList
for(Iterator iter = list.iterator(); iter.hasNext(); ) {
System.out.println("next is: "+ iter.next());
}
// 将ArrayList转换为数组
String[] arr = (String[])list.toArray(new String[0]);
for (String str:arr)
System.out.println("str: "+ str);
// 清空ArrayList
list.clear();
// 判断ArrayList是否为空
System.out.println("ArrayList is empty: "+ list.isEmpty());
}
}
四/其它
1. 连接两个数组 // 这个是Apache提供的class org.apache.commons.lang.ArrayUtils
- int[] intArray = { 1, 2, 3, 4, 5 };
- int[] intArray2 = { 6, 7, 8, 9, 10 };
- // Apache Commons Lang library
- int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
2. 把提供的数组元素放入一个字符串 //这个是Apache提供的class
- // containing the provided list of elements
- // Apache common lang
- String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
- System.out.println(j);
- // a, b, c
3. 移除数组中的元素 // 这个是Apache提供的class org.apache.commons.lang.ArrayUtils
- int[] intArray = { 1, 2, 3, 4, 5 };
- int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
- System.out.println(Arrays.toString(removed));
4. 将整数转换为字节数组
- byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
- for (byte t : bytes) {
- System.out.format("0x%x ", t);
- }
参考: