我试图加载电影文件,然后找出电影的类型。基本上如果电影类型不同,则每个类型将被放置在链接列表中的位置。例如,如果我有
Action Drama Comedy每个动作片将被放置在一个链接列表数组中,因此如果电影是动作,它就会被置于行动之下。必须通过找出类型的哈希码来做到这一点。
这是HashMap
类:
public class HashMap<KeyType,DataType>
{
private int count;
private int size;
private List<HashEntry<KeyType,DataType>> [] table;
public HashMap() {
}
public HashMap(int num)
{
size = num;
table = new List[num];
for(int i = 0; i < num; i++){
table[i] = new List<HashEntry<KeyType,DataType>>();
}
}
public void insert(KeyType key, DataType data){
if(key != null && data != null){
int hash = key.hashCode() % size;
HashEntry<KeyType, DataType> obj = new HashEntry(key, data);
table[hash].append(obj);
count++;
}
}
public void display(){
for(int i = 0 ; i < size; i++){
System.out.println("tables" + i + " ");
table[i].display();
}
}
public DataType find(KeyType key){
int hash = key.hashCode()% size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
return iter.item().getData();
}
iter.advance();
}
return null;
}
public void remove(KeyType key){
int hash = key.hashCode() % size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
list.remove(iter);
}
iter.advance();
}
}
这是我正在进行的LoadingMovies
课程:
private static final int size = 100;
private static HashMap<String, List<Movies>> movieGenres = new HashMap<String,List<Movies>>(size);
public static void loadMovies(String filename) throws FileNotFoundException{
String split = ","; //split with comma
Scanner in = new Scanner(new File(filename));
//ArrayList<Movies> arraylist = new ArrayList<>();
String wordIn;
Movies movie = new Movies();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String movieTitle = splitter[0];
String movieGenre = splitter[1];
String ageRating = splitter[2];
double scoreRating = Double.parseDouble(splitter[3]);
movie.setTitle(movieTitle);
movie.setGenre(movieGenre);
movie.setAgeRating(ageRating);
movie.setScoreRating(scoreRating);
List<Movies> moviesInThisGenre = movieGenres.find(movie.getGenre());
if (moviesInThisGenre == null) {
moviesInThisGenre = new List<>();
movieGenres.insert(movie.getGenre(), moviesInThisGenre);
}
ListIterator<Movies> iter = moviesInThisGenre.getIterator();
moviesInThisGenre.add(iter, movie);
}
movieGenres.display();
}
当我运行这个时,我得到了这个,它指向我在hashmap类中的find方法:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -72
at TheMoviePackage.HashMap.find(HashMap.java:53)
at TheMoviePackage.LoadingMovies.loadMovies(LoadingMovies.java:50)
at TheMoviePackage.LoadingMovies.main(LoadingMovies.java:66)
Java结果:1 建立成功(总时间:7秒)
我做错了什么?感谢
答案 0 :(得分:0)
由于你必须使用你自己的类型,我认为你的哈希码是负数所以它给你负数组索引,在索引上添加Math.abs它应该没问题。