0
点赞
收藏
分享

微信扫一扫

关于数组的基本知识


很惭愧,用java4年多了,一直都没有记住java数组的初始化方式,之前都是用arraylist的,现在记录一下


基础知识

package toyprogram;


/**
* This class is used for ...
*
* @author dlf(460795365@qq.com)
* @version 1.0, 2016年9月13日 下午3:39:42
*/
public class AboutArrayl {


@SuppressWarnings("unused")
public static void main(String[] args) {
int[] a = { 2, 3 };
int[] b = new int[5];
int[] c = new int[] { 1, 8 };
b[0] = 10;
System.out.println(b.length); // output 5


int[][] i = { { 1, 2, 3 }, { 2, 3, 4 }, { 1, 3, 4 } };
String s[][];
s = new String[3][];
s[0] = new String[2];
s[1] = new String[3];
s[2] = new String[2];


int a1[][] = new int[10][10];
int[][] a2 = new int[10][10];
int[] a3[] = new int[10][10];

//下面的两个 是错误的
// int a4[][] = new int[][];
// int a5[10][10] = new int[][];
}


}


ArrayList转化为数组

//ArrayList.java
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}



数组转化成Arraylist

方法一

String[] userid = {"aa","bb","cc"};
List<String> userList = new ArrayList<String>();
Collections.addAll(userList, userid);

//Collections.java
public static <T> boolean addAll(Collection<? super T> c, T... elements) {
boolean result = false;
for (T element : elements)
result |= c.add(element);
return result;
}

很奇怪result |= c.add(element);就等于result=result| c.add(element);


添加10个元素,如果每个都失败了,addAll整体才会返回false,只要有一个成功,返回的就是true


//Arraylist.java
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

返回的都是true!!



方法二

String[] userid = {"aa","bb","cc"};
List<String> userList = Arrays.asList(userid);

另:Arrays.asList()返回一个受指定数组支持的固定大小的列表。所以不能做Add、Remove等操作。

如果进行add,remove操作会咋样呢?

简单呀,报错:Exception in thread "main" java.lang.UnsupportedOperationException

List list = new ArrayList(Arrays.asList(userid));这样操作就可以了。
不过为啥Arrays.asList()返回一个受指定数组支持的固定大小的列表?
看源码呗

//Arrays.java
public static <T> List<T> asList(T... a) {
return new ArrayList<>(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 final E[] a;


ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
.......
}

大大的final看到了吗?

//

随后补充

因为E[] a 被final修饰所以报出了Exception in thread "main" java.lang.UnsupportedOperationException这个错误么?

错了,final修饰了某个变量,那么我仍然可以修改这个变量本身,但是不能修改它在内存中的位置

例如 final Person p=new Person();

然后我可以调用p.setName,调用几次都行,但是我不能再次new一个person给p,例如:p=new Person();

所以报的错误和final无关


那么到底是怎么回事呢?

java.util.Arrays.ArrayList继承自AbstractList,而AbstractList的add方法如下:

<strong><span style="color:#cc0000;">    //AbstractList.java
public boolean add(E e) {
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}</span></strong>

/


举报

相关推荐

0 条评论