实现ArrayList类,定义为MyArrayList.
package practice.collections.myArrayList;
/**
* 实现ArrayList类
*
* @param <T>
*/
public class MyArrayList<T> {
private int capacity = 10;
private int size = 0;
private T[] elementData = null;
@SuppressWarnings("unchecked")
public MyArrayList(){
elementData = (T[])new Object[capacity];
}
//add()
public void add(T t){
if(null == t){
throw new RuntimeException("要添加的值为空!");
}
if(size >= capacity){
ensureCapacity();
}
elementData[size++] = t;
}
//remove()
public void remove(int index){
if(index < 0 || index >= size){
throw new RuntimeException("索引超出范围!");
}
int length = size - index - 1;
System.arraycopy(elementData, index+1, elementData, index, length);
size--;
elementData[size] = null;
}
//get()
public T get(int index){
if(index < 0 || index >= size){
throw new RuntimeException("索引超出范围!");
}
return elementData[index];
}
public int size(){
return this.size;
}
//扩容
@SuppressWarnings("unchecked")
private void ensureCapacity() {
capacity = 2*capacity;
T[] newElementData = (T[])new Object[capacity];
System.arraycopy(elementData, 0, newElementData, 0, size);
elementData = newElementData;
}
}
先定义桶数组元素类型
package practice.collections.myHashMap;
public class Entry<K, V> {
protected K key;
protected V value;
protected Entry<K, V> next;
public Entry(K key,V value,Entry<K,V> next){
this.key = key;
this.value = value;
this.next = next;
}
}
再定义MyHashMap
package practice.collections.myHashMap;
/**
* 实现HashMap类
*
*/
public class MyHashMap<K,V> {
protected int capacity = 16;
protected int size = 0 ;
Entry<K,V>[] table = null;
@SuppressWarnings("unchecked")
public MyHashMap(){
table = new Entry[capacity];
}
public void put(K key,V value){
if(null == key){
throw new RuntimeException("the key should not be null.");
}
int i = key.hashCode()%capacity;
for(Entry<K, V> e = table[i];e != null;e = e.next){
if(e.key.equals(key)){
e.value = value;
return;
}
}
//若在链表中未找到key,则新建该key的节点,并将其作为新的table[i]
table[i] = new Entry<K, V>(key, value, table[i]);
size++;
}
public V get(K key){
if(null == key){
throw new RuntimeException("the key should not be null.");
}
int i = key.hashCode()%capacity;
for(Entry<K, V> e = table[i];e != null;e = e.next){
if(e.key.equals(key)){
return e.value;
}
}
return null;
}
public V remove(K key){
if(null == key){
throw new RuntimeException("the key should not be null.");
}
int i = key.hashCode()%capacity;
Entry<K, V> pre = table[i];
for(Entry<K, V> e = table[i];e != null;e = e.next){
if(e.key.equals(key)){
if(pre == e)
table[i] = e.next;
else
pre.next = e.next;
return e.value;
}
pre = e; //注重保持一个前缀的方法
}
return null;
}
}
以上MyHashMap未考虑扩容,感觉比较复杂