- No.1
- 参考博客,对ArrayList和LinkedList进行测试.
- 调用assertEquals方法,对ArrayList的add,remove和isEmpty方法以及LinkedList的add,remove和contains方法进行测试
- No.2
- 对两个非递减线性表进行合并后排序
package ExInClass.FirstExp;
/**
* Created by dell on 2017/9/26.
*/
import java.util.ArrayList;
import java.util.List;
public class MergeSort {
public static List <? extends Comparable> mergeSortedList(List <? extends Comparable> aList, List <? extends Comparable> bList) {
List mergeList = new ArrayList();
while (true) {
if (bList.get(0).compareTo(aList.get(0)) < 0) {
mergeList.add(bList.get(0));
bList.remove(0);
} else if (bList.get(0).compareTo(aList.get(0)) == 0) {
mergeList.add(bList.get(0));
bList.remove(0);
mergeList.add(aList.get(0));
aList.remove(0);
} else if (bList.get(0).compareTo(aList.get(0)) > 0) {
mergeList.add(aList.get(0));
aList.remove(0);
}
if (aList.isEmpty() || bList.isEmpty()) {
break;
}
}
if (!aList.isEmpty()) {
for (int i = 0; i < aList.size(); i++) {
mergeList.add(aList.get(i));
}
} else if (!bList.isEmpty()) {
for (int i = 0; i < bList.size(); i++) {
mergeList.add(bList.get(i));
}
}
return mergeList;
}
}
- No.3
- 用数组实现线性表List,并对ArrayList进行测试
package ExInClass.FirstExp;
/**
* Created by dell on 2017/9/27.
*/
import junit.framework.TestCase;
public class MyArrayListTest extends TestCase {
public void testIsEmpty() throws Exception {
assertEquals(true, new ArrayList().isEmpty());
}
public void testAdd() throws Exception {
ArrayList bag = new ArrayList();
bag.add(1);
assertEquals(true, bag.add(5));
}
@org.junit.Test
public void testremove() throws Exception {
ArrayList bag = new ArrayList();
bag.add(5);
bag.add(4);
assertEquals(false, bag.remove(4));
}
}
- No.4
- 用链表实现线性表List,并对LinkedList进行测试
package ExInClass.FirstExp;
/**
* Created by dell on 2017/10/1.
*/
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class MyLinkedListTest {
@Test
public void add(){
MyLinkedList LinkedList = new MyLinkedList();
LinkedList.add(3);
LinkedList.add(12);
assertEquals(true, LinkedList.add(2));
}
@Test
public void remove(){
MyLinkedList LinkedList = new MyLinkedList();
LinkedList.add(22);
assertEquals(22, LinkedList.remove());
}
@Test
public void contains(){
MyLinkedList LinkedList = new MyLinkedList();
LinkedList.add(12);
LinkedList.add(21);
assertEquals(true, LinkedList.contains(21));
}
}
- No.5
-
分析ArrayList和LinkedList的源代码,首先是先摸清它的属性,再研究它的构造方法和其他的一些方法。
-
阅读大神的博客让我对源代码的分析有很大的启发
-
方法之中会调用其他方法是非常常见的,所以关联地来分析是十分有用的,并且还可以对有些门道的方法进行深入的分析
-
下面是对add(E e)方法的分析
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
先调用了ensureCapacity(size+1)方法,后将元素的索引赋给elementData[size],而后size++自增++。++ensureCapacity(size+1)++确保了数组不会出现越界的情况。
根据ensureCapacity的方法名可以知道是确保容量用的。ensureCapacity(size+1)后面的注释可以明白是增加modCount的值