我想写一个类似hashMap的一个函数,用Key——Valu模式存储和查询,结果出了问题,情大家帮忙看看,感激不尽!下面是代码:HostKey 类相当于HaspMap类package test;import java.util.Vector;/**
*
* @author Administrator
*/ class HostKey {
static Vector Address=new Vector(100,10);
static Vector keys=new Vector(100,10); public static void put(String addr,String key){
String addr1=null;String key1=null;
addr1=addr;key1=key;
Address.addElement(addr1);
keys.addElement(key1);
}
public static String getKey(String addr){
int index;
index=Address.indexOf(addr);
return (String)keys.elementAt(index);
}
}
以下是调用:/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/package test;
import java.util.Vector;
/**
*
* @author Administrator
*/
public class Main { /**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HostKey.put("1111", "2222");
HostKey.put("3333", "4444");
HostKey.put("5555", "6666");
HostKey.put("7777", "8888");
System.out.println(HostKey.getKey("1111"));
System.out.println(HostKey.getKey("2222"));
System.out.println(HostKey.getKey("3333"));
System.out.println(HostKey.getKey("4444"));
}}/**
*
* @author Administrator
*/出现以下错误:1
1111
2
3333
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
5555
4
at java.util.Vector.elementAt(Vector.java:430)
7777
at test.HostKey.getKey(HostKey.java:34)
getKeytrue
at test.Main.main(Main.java:26)
index0
2222
getKeyfalse
index-1
Java Result: 1
成功生成(总时间:0 秒)
*
* @author Administrator
*/ class HostKey {
static Vector Address=new Vector(100,10);
static Vector keys=new Vector(100,10); public static void put(String addr,String key){
String addr1=null;String key1=null;
addr1=addr;key1=key;
Address.addElement(addr1);
keys.addElement(key1);
}
public static String getKey(String addr){
int index;
index=Address.indexOf(addr);
return (String)keys.elementAt(index);
}
}
以下是调用:/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/package test;
import java.util.Vector;
/**
*
* @author Administrator
*/
public class Main { /**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HostKey.put("1111", "2222");
HostKey.put("3333", "4444");
HostKey.put("5555", "6666");
HostKey.put("7777", "8888");
System.out.println(HostKey.getKey("1111"));
System.out.println(HostKey.getKey("2222"));
System.out.println(HostKey.getKey("3333"));
System.out.println(HostKey.getKey("4444"));
}}/**
*
* @author Administrator
*/出现以下错误:1
1111
2
3333
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
5555
4
at java.util.Vector.elementAt(Vector.java:430)
7777
at test.HostKey.getKey(HostKey.java:34)
getKeytrue
at test.Main.main(Main.java:26)
index0
2222
getKeyfalse
index-1
Java Result: 1
成功生成(总时间:0 秒)
int index;
index = Address.indexOf(addr);
if(index == -1) {
return null;
}
return (String) keys.elementAt(index);
}
没有找到的情况