getting an array index out of a bound exception in below code. I have tried to put the error line inside try-catch, putting try catch also throwing an error in eclipse. can anyone pls tell me what I am doing wrong.
Error:
"Multiple markers at this line
- Syntax error on token "try", invalid
Modifiers
- Syntax error, insert "}" to complete
Block"
With try catch:
try {
public hashMapimpl() {
table =new Entry[5];
}}catch(Exception e)
{
e.getMessage();
}
Complete code:
import java.util.Map.Entry;
class hashMapimpl<K,V> {
static int capacity=5;
private Entry<K,V> [] table;
static class Entry<K, V>{
K key;
V value;
Entry<K,V> next;
public Entry(K key,V value, Entry<K,V> next)
{
this.key=key;
this.value=value;
this.next=next;
}
}
public hashMapimpl() {
table =new Entry[capacity];
}
public void put(K newKey, V data) {
if(newKey==null) {
return;
}
int hash=hash(newKey);
Entry<K,V> newentry = new Entry<K,V>(newKey,data,null);
if(table[hash]==null)
table[hash]=newentry;
else {
Entry<K,V> previous =null;
Entry<K,V> current=table[hash];
while(current!=null)
{
if(current.key.equals(newKey))
{
if(previous==null) {
newentry.next=current.next;
table[hash]=newentry;
return;}
else {
newentry.next=current.next;
table[hash]=newentry;
return;
}
}
previous=current;
current=current.next;
}
previous.next=newentry;
}
}
public V get(K key) {
int hash=hash(key);
if(table[hash]==null) {
return null;
}
else {
Entry<K,V> temp=table[hash];
while(temp!=null)
{
if(temp.key.equals(key))
temp=temp.next;
return temp.value;
}
return null;
}
}
public void display()
{
for(int i=0;i<capacity;i++) {
if(table[i]!=null) {
Entry<K,V> e=table[i];
while(e!=null)
{
System.out.println(e.key);
System.out.println(e.value);
e=e.next;
}
}
}
}
private int hash(K Key) {
return Math.abs(Key.hashCode());
}
public static class hashmap_main{
public static void main(String[] args)
{
hashMapimpl<Integer,Integer> h1 = new hashMapimpl<Integer,Integer>();
h1.put(2, 4);
h1.put(4, 0);
h1.put(23, 9);
h1.put(1, 8);
System.out.println(h1.get(23));
}
}
}