I wrote a HashMap implementation for simple integer-string key-values in Java. In attempting to test it, I wrote some test code, and saw that for between 0-4 of the values (out of a sample of 5000) each time, the test was failing. So I then switched my HashMap to the Java default implementation, and noticed that my tests were failing the obviously correct implementation. So, I have been hung up for the past couple hours trying to figure out why my test is failing. Is there something I am missing? (Well, obviously there is...)
Here is my code:
package HashMapOther;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;
public class StudentStore {
private static SecureRandom random = new SecureRandom();
static HashMap<Integer, String> map;
static String[] studentNames;
static int[] keys;
static int magicNumber =5000; //still fails no matter size
public static void main(String[] args){
long startTime = System.currentTimeMillis();
start();
test();
long endTime = System.currentTimeMillis();
System.out.println("TIME: " + (endTime - startTime) + " ms");
}
public static void start(){
studentNames = getStudents(); //random strings
keys = getKeys(); //random integers
map = new HashMap<Integer, String>(magicNumber, (float) 0.7);
for(int i=0; i< magicNumber; i++){
map.put(keys[i],studentNames[i]);
}
}
public static int[] getKeys(){ //random integers
int[] a = new int[magicNumber];
for(int k=0; k< magicNumber; k++){
a[k] = (int) (Math.random()*10000000+1);
}
return a;
}
public static String[] getStudents(){ //random strings
String[] temp = new String[magicNumber];
for(int i=0; i<magicNumber; i++){
temp[i] = randomString();
}
return temp;
}
public static String randomString(){ //random string
return new BigInteger(130, random).toString(32);
}
public static void test(){ //test code
boolean passed = true;
for(int i=0; i<magicNumber; i++){
if(!studentNames[i].equals(map.get(keys[i]))){
System.out.println("FAILURE: "+studentNames[i] + " " + map.get(keys[i]));
passed = false;
}
}
System.out.println("RESULT: " + passed);
}
}
And here is sample output:
FAILURE: vq0cpihdsr4vfru6126suufvp4 3dq4shra6dps49psehqjuof4ib
FAILURE: lo2t73n1upqk6cmirdpui29ndt r6accv6ja5pkv723c5g0fe0d1q
RESULT: false
TIME: 94 ms
or, in another run:
RESULT: true
TIME: 104 ms
and, another:
FAILURE: c7848b9rejbtguj2d70llotvpu od7r0fjdphvdli6mgonbictg4d
FAILURE: 4ouk2cj9ipoo4hjrco8vd6p7e kt0u925jdn102cjul96thsfhcm
FAILURE: 2spd0u9lp7531hm09rqu8oncvm scrui9hl7tr0aq85at13oekgf7
RESULT: false
TIME: 99 ms
Aucun commentaire:
Enregistrer un commentaire