實現ArrayList和HashMap類

2021-07-22 01:48:46 字數 1669 閱讀 4475

實現arraylist類,定義為myarraylist.

package practice.collections.myarraylist;

/** * 實現arraylist類

* * @param */

public class myarraylist

//add()

public void add(t t)

if(size >= capacity)

elementdata[size++] = t;

} //remove()

public void remove(int index)

int length = size - index - 1;

system.arraycopy(elementdata, index+1, elementdata, index, length);

size--;

elementdata[size] = null; }

//get()

public t get(int index)

return elementdata[index]; }

public int size()

//擴容

@suppresswarnings("unchecked")

private void ensurecapacity()

}

實現hashmap類,類名為myhashmap

先定義桶陣列元素型別

package practice.collections.myhashmap;

public class entry

}

再定義myhashmap

package practice.collections.myhashmap;

/** * 實現hashmap類

* */

public class myhashmap

public void put(k key,v value)

int i = key.hashcode()%capacity;

for(entrye = table[i];e != null;e = e.next)

} //若在鍊錶中未找到key,則新建該key的節點,並將其作為新的table[i]

table[i] = new entry(key, value, table[i]);

size++; }

public v get(k key)

int i = key.hashcode()%capacity;

for(entrye = table[i];e != null;e = e.next)

} return null; }

public v remove(k key)

int i = key.hashcode()%capacity;

entrypre = table[i];

for(entrye = table[i];e != null;e = e.next)

pre = e; //注重保持乙個字首的方法

} return null; }

}

以上myhashmap未考慮擴容,感覺比較複雜

實現ArrayList和迭代器

public class diyarraylist t implements iterable t public diyarraylist int capacity catch illegalacces ception e data t new object capacity this size 0...

Array List和ArrayList的區別與

定義 public abstract class array icloneable,ilist,icollection,ienumerable,istructuralcomparable,istructuraequatable 陣列在記憶體中是連續儲存的,所以它的索引速度是非常的快,而且賦值與修改元...

ArrayList底層實現和原理分析

今天是週末,沒什麼事就在家裡看了一下原始碼,我習慣使用jdk1.8,所以我的 全都是基於jdk1.8,好了下面是正文,今天來說說arraylist的底層實現和源 首先,集合arraylist是list的實現類,list還有兩個實現類linkedlist和vector。先說說這幾個實現類的區別吧 1....