Java泛型:包含数组泛型

编程入门 行业动态 更新时间:2024-10-27 22:23:18
本文介绍了Java泛型:包含数组泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:结果  的Java如何:通用阵列创建结果  错误通用阵列创建

我一直负责Java编写一个哈希表,它必须与任何数据类型。都在code我写的规则如下: - 散列表必须有一个数组为标的数据结构,在当时确定的大小的对象被构​​造 - 当碰撞发生时,碰撞应放入一个链表的元件,其中包含的所有元件中的该索引(key)的哈希表

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 )。

前往该项目的人也是不确定如何处理这个问题。有什么办法,我可以改变我的code,使哈希表仍然有一个数组作为其底层的数据结构与碰撞被放置在一个链表?

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));

是的,构造函数产生一个警告(即解释了未登记的注释),但事后code工作没有更多的警告。

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

更多推荐

Java泛型:包含数组泛型

本文发布于:2023-11-16 17:30:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Java   泛型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!