Advertisement
gowtham900

unsortedTableMap

Oct 22nd, 2021
1,376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3.  
  4. public class UnsortedTableMap <K,V> extends AbstractMap{
  5.     private ArrayList<MapEntry<K,V>>table=new ArrayList<>();
  6.     public UnsortedTableMap(){
  7.  
  8.     }
  9.     private int findIndex(K,key){
  10.         int n=table.size();
  11.         for(int j=0;j<n;j++)
  12.             if(table.get(j).getKey().equals(key))
  13.                 return j;
  14.             return -1;
  15.     }
  16.     public int size(){
  17.         return table.size();
  18.     }
  19.     public V get(K key){
  20.         int j=findIndex(key);
  21.         if(j==-1){
  22.             table.add(new MapEntry<>(key,value));
  23.             return null;
  24.         }else
  25.             return table.get(j).setValue(value);
  26.     }
  27.     public V remove(K key){
  28.         int j=findIndex(key);
  29.         int n=size();
  30.         if(j==-1) return null;
  31.         V answer=table.get(j).getValue();
  32.         if(j!=n-1)
  33.             table.set(j,table.get(n-1));
  34.         table.remove(n-1);
  35.         return answer;
  36.     }
  37.     private class EntryIterator implements Iterator<Entry<K,V>>{
  38.         private int j=0;
  39.  
  40.  
  41.         public boolean hasNext() {
  42.             return j<table.size();
  43.         }
  44.         public Entry<K,V>next(){
  45.             if(j==table.size()) throw new UnsupportedOperationException();}
  46.  
  47.         }
  48.         private class EntryIterable implements Iterable<Entry<K,V>>{
  49.         public Iterator<Entry<K,V>>iterator(){
  50.             return new EntryIterator();
  51.         }
  52.         public Iterable<Entry<K,V>>entrySet(){
  53.             return new EntryIterable();
  54.         }
  55.  
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement