Você está na página 1de 5

package Topic1;

/** * Created with IntelliJ IDEA. * User: eefremova * Date: 10/17/13 * Time: 2:53 PM * To change this template use File | Settings | File Templates. */ import java.util.ArrayList;

public class Hashtable {

private ArrayList keys;

private ArrayList values;

public Hashtable() { keys = new ArrayList(); values = new ArrayList(); }

/**

* @return if the key was previously associated with another value, returns * * */ public Object put(Object key, Object value) { Object result = null; if (keys.size()>0) { for (int i = 0; i<keys.size(); i++) { a specified value associated with specified key, otherwise returns null

if (keys.get(i) == key) { result = values.get(i); values.set(i, value); } } } if (result == null) { keys.add(key); values.add(value); } return result; }

/** * @return a value, associated with specified key, returns null if key is * not associated with any value

*/ public Object get(Object key) { Object result = null; if (keys.size() > 0) { for (int i = 0; i<keys.size(); i++) { if (keys.get(i) == key) { result = values.get(i); } } }

return result; }

/** * @return returns previously associated value or null if key was not * */ public Object remove(Object key) { Object result = null; if (keys.size() > 0) { for (int i = 0; i<keys.size(); i++) { if (keys.get(i) == key) { result = values.get(i); keys.remove(i); associated with any value

values.remove(i); } } }

return result;

public void printTable() { System.out.println("Hash table: "); if (keys.size() > 0 ) { for (int i = 0; i<keys.size(); i++) { System.out.print(keys.get(i)+":"+values.get(i)+" "); } } System.out.println();

public static void main(String[] args) { Hashtable hashTable = new Hashtable(); hashTable.put(1, 10); hashTable.put(2, 20);

hashTable.put(3, 30); hashTable.put(4, 40); hashTable.printTable(); hashTable.remove(1); hashTable.printTable();

Você também pode gostar