Arraylist e Hashmap
O armazenamento do Arraylist é uma matriz.
O armazenamento do Hashmap é uma matriz mais uma lista vinculada.
O seguinte MyArrayList e MyHashmap não são usados no trabalho real. A coisa mais provável a usar é entrevistar e encontrar um emprego e enganar os outros. Embora não seja útil no trabalho, isso não significa que seja inútil. Pode nos ajudar a entender seus princípios de implementação. Após a conclusão da implementação, verificaremos cuidadosamente o código -fonte no JDK e descobriremos onde outras pessoas podem aprender em sua implementação.
MyArraylist
classe pública MyArrayList <e> {private int capacidade = 10; private int tamanho = 0; privado e [] valores = nulo; @Suppresswarnings ("desmarcado") public myArrayList () {valores = (e []) novo objeto [capacidade]; } @Suppresswarnings ("desmarcado") public myArrayList (intacabilidade int) {this.capacity = capacidade; valores = (e []) novo objeto [this.capacity]; } public void put (e e) {if (e == null) {lança a nova execução de tempo de exceção ("o valor não deve ser nulo."); } if (size> = capacidade) {ALARGECAPACIDADE (); } valores [tamanho] = e; tamanho ++; } public e get (int index) {if (index> = size) {lança nova run timeException ("o índice:" + index + "está fora da banda."); } retornar valores [index]; } public void Remow (int index) {if (index> = size) {tiro novo RUNTimeException ("O índice:" + index + "está fora da banda."); } para (int i = index; i <tamanho - 1; i ++) {valores [i] = valores [i+1]; } valores [tamanho - 1] = null; tamanho--; } @Suppresswarnings ("desmarcado") private vazio ALARGECAPACACIDADE () {Capacidade = Capacidade * 2; E [] tmpValues = (e []) novo objeto [capacidade]; System.arraycopy (valores, 0, tmpValues, 0, tamanho); valores = tmpValues; } public string tostring () {stringbuilder sb = new stringbuilder (); sb.append ("["); for (int i = 0; i <tamanho; i ++) {sb.append (valores [i]). Append (","); } if (size> 0) {sb.deleteCharat (sb.length () - 1); } sb.append ("]"); return sb.toString (); } / ** * @param args * / public static void main (string [] args) {MyArrayList <String> myList = new MyArrayList <String> (); myList.put ("1"); myList.put ("2"); myList.put ("3"); myList.put ("4"); myList.put ("5"); myList.put ("6"); myList.put ("7"); myList.put ("8"); myList.put ("9"); myList.Remove (7); System.out.println (myList.toString ()); }} MyHashmap
classe pública myHashmap <k, v> {// capacidade de inicialização private int capacidade = 10; // Total Entidades Privado Int Tamanho = 0; entidade privada <k, v> [] entidades = null; @Suppresswarnings ("desmarcado") public myhashmap () {entities = nova entidade [capacidade]; } public void put (K -Key, V Value) {if (key == null) {tiro novo RuntimeException ("A chave é nula"); } rehash (); Entidade <k, v> newentity = nova entidade <k, v> (chave, valor); put (newentity, this.entities, this.capacity); } Void privado Put (entidade <k, v> Newentity, entidade <k, v> [] entidades, int capacidade) {int index = newentity.getKey (). hashcode () % capacidade; Entidade <k, v> entidade = entidades [índice]; Entidade <k, v> Firstentity = entidades [índice]; if (entity == null) {entidades [index] = newentity; tamanho ++; } else {if (newentity.getKey (). Equals (entity.getKey ())) {// Encontre a mesma chave para a primeira entidade, se encontrar, substituir o valor antigo pelo novo valor NewEntity.setNext (entity.getNext ()); newentity.setpre (entity.getpre ()); if (entity.getNext ()! = null) {entity.getNext (). setPre (NewEntity); } entidades [index] = newentity; } else if (entity.getNext ()! = null) {while (entity.getNext ()! = null) {// Encontre a mesma chave para toda a próxima entidade, se encontrar, substitua o valor antigo para o novo valor Entity = entity.getNext (); if (newentity.getKey (). Equals (entity.getKey ()))) {newentity.setpre (entity.getpre ()); newentity.setNext (entity.getNext ()); if (entity.getNext ()! = null) {entity.getNext (). setPre (NewEntity); } entidades [index] = newentity; retornar; }} // Não é possível encontrar a mesma chave e insira a nova entidade no cabeçalho Newentity.SetNext (Firstentity); newentity.setpre (Firstentity.getPre ()); Firstity.SetPre (Newentity); entidades [index] = newentity; tamanho ++; } else {// não consegue encontrar a mesma chave e, em seguida, coloque a nova entidade na cabeça newentity.setNext (Firstentity); Firstity.SetPre (Newentity); entidades [index] = newentity; tamanho ++; }}} public v get (k key) {if (key == null) {tiro novo RuntimeException ("A chave é nula"); } int index = key.hashcode () % capacidade; Entidade <k, v> entidade = entidades [índice]; if (entity! = null) {if (entity.getKey (). igual (key)) {return entity.getValue (); } else {entity = entity.getNext (); while (entidade! = null) {if (entity.getKey (). igual (key)) {return entity.getValue (); } entity = entity.getNext (); }}} retornar nulo; } public void Remover (K -key) {if (key == null) {lança a nova RunTimeException ("A chave é nula"); } int index = key.hashcode () % capacidade; Entidade <k, v> entidade = entidades [índice]; if (entity! = null) {if (entity.getKey (). Equals (key)) {if (entity.getNext ()! = null) {// remova a primeira entidade entidade.getNext (). setPre (entity.getpre ()); entidades [index] = entity.getNext (); entidade = nulo; } else {// esvazia essas entidades de índice [index] = null; } tamanho--; } else {entity = entity.getNext (); while (entidade! = null) {if (entity.getKey (). igual (key)) {if (entity.getNext ()! = null) {entity.getpre (). setNext (entity.getNext ()); entity.getNext (). setPre (entity.getpre ()); entidade = nulo; } else {// libere a entidade encontrada entidade.getpre (). setNext (null); entidade = nulo; } tamanho--; retornar; } entity = entity.getNext (); }}}} public string tostring () {stringbuilder sb = new stringbuilder (); for (int i = 0; i <capacidade; i ++) {sb.append ("index ="). Append (i) .append ("["); Boolean hasentity = false; Entidade <k, v> entidade = entidades [i]; if (entidade! = null) {hasentity = true; } while (entity! = null) {sb.append ("["). append (entity.getKey ()). append ("="). append (entity.getValue ()). append ("]"). append (","); entity = entity.getNext (); } if (hasentity) {sb.deleteCharat (sb.length () - 1); } sb.append ("]/n"); } return sb.toString (); } / ** * Estratégia simples de re-hash, se o tamanho for maior que a capacidade, re-hash de ação * / private void rehash () {if (size> = capacidade) {int newCapacity = capacidade * 2; @Suppresswarnings ("desmarcado") entidade <k, v> [] newentities = nova entidade [newcapacity]; for (int i = 0; i <capacidade; i ++) {entidade <k, v> entity = entidades [i]; while (entidade! = null) {put (entidade, newentities, newcapacity); entity = entity.getNext (); }} this.Capacity = newCapacity; this.entities = Newentities; }} public static void main (string [] args) {myhashmap <string, string> map = new myHashmap <string, string> (); map.put ("One", "1"); map.put ("dois", "2"); map.put ("três", "3"); map.put ("quatro", "4"); map.put ("cinco", "5"); map.put ("Six", "6"); map.put ("sete", "7"); map.put ("oito", "8"); map.put ("Nove", "9"); map.put ("ten", "10"); System.out.println (map.get ("One")); System.out.println (map.get ("dois")); System.out.println (map.get ("três")); System.out.println (map.get ("quatro")); System.out.println (map.get ("cinco")); System.out.println (map.get ("six")); System.out.println (map.get ("sete")); System.out.println (map.get ("oito")); System.out.println (map.get ("nine")); System.out.println (map.get ("ten")); System.out.println (map.toString ()); map.remove ("nove"); map.remove ("três"); System.out.println (map.get ("One")); System.out.println (map.get ("dois")); System.out.println (map.get ("três")); System.out.println (map.get ("quatro")); System.out.println (map.get ("cinco")); System.out.println (map.get ("six")); System.out.println (map.get ("sete")); System.out.println (map.get ("oito")); System.out.println (map.get ("nine")); System.out.println (map.get ("ten")); System.out.println (map.toString ()); }} entidade da classe <k, v> {private k key; Valor V Privado; entidade privada <k, v> pre; entidade privada <k, v> Em seguida; entidade pública (K -Key, V valor) {this.key = key; this.value = value; } public k getKey () {return Key; } public void setKey (K -Key) {this.key = key; } public v getValue () {return value; } public void SetValue (Value V) {this.value = value; } entidade pública <k, v> getpre () {return pre; } public void setPre (entidade <k, v> pre) {this.pre = pre; } entidade pública <k, v> getNext () {return a seguir; } public void setNext (entidade <k, v> a seguir) {this.Next = a seguir; }}Obrigado pela leitura, espero que isso possa ajudá -lo. Obrigado pelo seu apoio a este site!