最近比较有时间啦,有时间搞下java,个人觉得学这门语言语法太多啦,不一一去学习啦,心血来潮,挂了个struct2的源代码,一入深似海啊,看得我天花缭乱,从最简单的开始吧
1publicstaticvoidmain(String[] args) {23Vector v =newVector(4);45//向Vector中添加元素 静态数组+动态扩展6//使用add方法直接添加元素7v.add("Test0");8v.add("Test1");9v.add("Test0");10v.add("Test2");11v.add("Test2");1213//从Vector中删除元素14v.remove("Test0");//删除指定内容的元素15v.remove(0);//按照索引号删除元素1617//获得Vector中已有元素的个数18intsize =v.size();19System.out.PRintln("size:" +size);2021//遍历Vector中的元素22for(inti = 0;i < v.size();i++){23System.out.println(v.get(i));24}25}
代码很简单啦,学过数据结构的都知道,简单的新增改查啦,不过我们要深入一下了解,这玩意跟数组有什么区别
构造函数如下,意思是说你可以初始化一个容量的数,多少你自己决定
1/**2* Constructs an empty vector with the specified initial capacity and3* with its capacity increment equal to zero.4*5*@paraminitialCapacity the initial capacity of the vector6*@throwsIllegalArgumentException if the specified initial capacity7* is negative8*/9publicVector(intinitialCapacity) {10this(initialCapacity, 0);11}
我们接着来看,java的构造函数可真的比php强大,支持不同参数调用,换php的话早就报错啦
1/**2* Constructs an empty vector with the specified initial capacity and3* capacity increment.4*5*@paraminitialCapacity the initial capacity of the vector6*@paramcapacityIncrement the amount by which the capacity is7* increased when the vector overflows8*@throwsIllegalArgumentException if the specified initial capacity9* is negative10*/11publicVector(intinitialCapacity,intcapacityIncrement) {12super();13if(initialCapacity < 0)14thrownewIllegalArgumentException("Illegal Capacity: "+15initialCapacity);16this.elementData =newObject[initialCapacity];17this.capacityIncrement =capacityIncrement;18}
代码是不是很简单,简单的初始化一个对象数组,连我一个高中生的看出来啦,注意到第二个参数,这个是控制数组填满了之后要怎么增加,可以理解为一个策略吧
我们来看看添加元素是怎样实现的
1/**2* Appends the specified element to the end of this Vector.3*4*@parame element to be appended to this Vector5*@return{@codetrue} (as specified by {@linkCollection#add})6*@since1.27*/8publicsynchronizedbooleanadd(E e) {9modCount++;10ensureCapacityHelper(elementCount + 1);11elementData[elementCount++] =e;12returntrue;13}
synchronized 这玩意就是多线程安全的时候用的,防止多个线程同事操作
关键是 ensureCapacityHelper 这个函数
1/**2* This implements the unsynchronized semantics of ensureCapacity.3* Synchronized methods in this class can internally call this4* method for ensuring capacity without incurring the cost of an5* extra synchronization.6*7*@see#ensureCapacity(int)8*/9privatevoidensureCapacityHelper(intminCapacity) {10intoldCapacity =elementData.length;11if(minCapacity >oldCapacity) {12Object[] oldData =elementData;13intnewCapacity = (capacityIncrement > 0) ?14(oldCapacity + capacityIncrement) : (oldCapacity * 2);15if(newCapacity <minCapacity) {16newCapacity =minCapacity;17}18elementData =Arrays.copyOf(elementData, newCapacity);19}20}
可以这么理解吧,上面这段代码就是看看数组满了没有,如果满了就动态的增加,还记得我们上面说的那个参数吗,就是可以理解为扩展因子,如果没有定义的话就double增加,就是这么简单,貌似跟c语言的动态数组好像啊
总结一下
上面我们学到的知识点
1. synchronized 同步用的,相当于一个锁吧
2. Arrays.copyOf 这函数是从一个数组复制到一个新数组里面,新数组容量可以自己定义
3. java 的构造函数可以支持多个,前提你每个构造函数的参数都不同
4. vector 这东西跟数组没什么区别,只不过它比静态数组可以自动扩展罢了
今天就到这里吧