简体   繁体   English

我知道Java不支持通用数组,但是我不知道如何解决这个问题,因此它可以正常工作

[英]I know that generic arrays are not supported by Java, but I don't know how to fix this so it will work

我正在尝试创建一个HashTable,代码的这一部分需要一个数组,但是当它不被泛型泛型时,我会得到未经检查的警告,但是我知道不支持泛型数组,但是我不确定如何解决这个问题。 。

array = new HashEntry<AnyType>[ nextPrime( arraySize ) ];

I suggest checking out JDK's own code for HashMap , specifically the resize method and these lines: 我建议检查一下JDK自己的HashMap代码,特别是resize方法和以下几行:

    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

newTab is then assigned to the main instance variable, table . 然后将newTab分配给主实例变量table So, if JDK can't avoid @SuppressWarnings , neither will you. 因此,如果JDK无法避免@SuppressWarnings ,那么您也不会。

Write it as such 这样写

@SuppressWarnings("unchecked")
HashEntry<K, V>[] array = new HashEntry[nextPrime()];

then add @SuppressWarnings("unchecked") to it. 然后向其添加@SuppressWarnings(“ unchecked”)。

Don't use arrays. 不要使用数组。 Use collections. 使用集合。

Using arrays requires more code, more care and gives no measurable benefit. 使用数组需要更多的代码,需要更多的照顾,并且无法带来可观的收益。

Using collections leverages the code and care built into the JDK. 使用集合利用了JDK中内置的代码和关怀。
If you've got an array of HashEntry, you're most of the way to a Map - just use a constant order map: 如果您有一个HashEntry数组,那么就很容易使用Map-只需使用恒定顺序的map:

Map<SomeKey, SomeValue> map = new LinkedHashMap<SomeKey, SomeValue>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java程序中出现ArrayIndexOutOfBoundsException错误,我不知道如何解决 - ArrayIndexOutOfBoundsException error in Java program, and I don't know how to fix it Bug的Java。 我不知道怎么解决 - Bug java. I don't know how to fix it 我不知道如何解决此NullPointerException - I don't know how to fix this NullPointerException 我是一个初学者程序员,我不知道 Java 中的参数是如何工作的。 那么它们是如何工作的呢? - I am a beginner programmer and I don't know how parameters work in Java. So how do they work? 试图在 Java 中使用数组,但不知道我做错了什么 - trying to work with arrays in java but don't know what i am doing wrong Java:我无法让它循环,布尔值有问题,但我不知道如何修复它 - Java: I can't get it to loop, somethings wrong with the boolean but I don't know how to fix it 当我不知道泛型对象的类型时,如何避免Java中未经检查的方法警告? - How can I avoid unchecked method warnings in Java when I don't know the type of a generic object? 我的代码出现错误,我不知道如何修复(Java fx stackPane) - I am getting errors in my code and i don't know how to fix(Java fx stackPane) 我正在用Java编写一个Android应用程序,我认为这是内存泄漏,并且不知道如何解决它 - I am writing an Android app in java with what I believe to be a memory leak and don't know how to fix it 我在 Java 中遇到三个错误,我不知道如何修复它们 - I am getting three errors in Java and I don't know how to fix them
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM