Java泛型:包含泛型的数组 [英] Java Generics: Array containing generics

查看:37
本文介绍了Java泛型:包含泛型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java 如何:创建通用数组
通用数组创建错误

我的任务是用 Java 编写哈希表,它必须适用于任何数据类型.我写的代码的规则如下:- 哈希表必须有一个数组作为底层数据结构,其大小在构造对象时确定- 当发生冲突时,应将发生冲突的元素放入一个链表中,该链表保存哈希表中该索引(键)处的所有元素

I have been tasked with writing a Hash Table in Java, which must work with any data type. The rules on the code I am writing are as follows: - The hash table must have an array as the underlying data structures, of a size determined at the time the object is constructed - When a collision occurs, the element that collides should be placed into a linked list, which holds all of the elements at that index (key) in the hash table

因此,对于底层数据类型,我制作了一个 LinkedList 类型的数组(自定义,而不是 Java API LinkedList).

Thus, for the underlying data type, I have made an array of type LinkedList (custom, not the Java API LinkedList).

private LinkedList<T>[] table;

问题当然是实例化这个数组.以下是我的一些尝试:

The issue is, of course, instantiating this array. Here are some of my attempts:

public HashTable(int size) {
  table = new LinkedList<T>[size];
}

这会引发编译时通用数组创建错误.

This throws a compile-time generic array creation error.

public HashTable(int size) {
  table = (LinkedList<T>[])(new Object[size]);
}

这会在运行时导致 ClassCastException 错误(java.lang.Object 不能转换为 LinkedList).

That causes a ClassCastException error at runtime (java.lang.Object cannot be cast to LinkedList).

项目负责人也不确定如何处理这个问题.有什么方法可以更改我的代码,以便哈希表仍然有一个数组作为其底层数据结构,并将冲突放置在 LinkedList 中?

The person heading the project is also unsure of how to deal with this issue. Is there any way I can change my code so that the hash table still has an array as its underlying data structure with the collisions being placed in a LinkedList?

推荐答案

这对我有用:

public class HashTable<T> {

    private LinkedList<T> table[];

    @SuppressWarnings("unchecked")
    public HashTable(int size) {
        table = new LinkedList[size];
    }

}

例如:

HashTable<String> t = new HashTable<String>(10);
t.table[0] = new LinkedList<String>();
t.table[0].add("test");
System.out.println(t.table[0].get(0));

是的,构造函数生成了一个警告(解释了unchecked"注释),但之后代码工作时没有更多警告.

Yes, the constructor generated a warning (that explains the "unchecked" annotation), but afterwards the code works without more warnings.

这篇关于Java泛型:包含泛型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆