So i have a class that takes 2 generics types: public class Something<K,V>....

In another class, i'm trying to create an array of Something objects. how do i do this? i'm getting an error with this: Something <K,V>[] s = (K,V[]) new Object[size];

Recommended Answers

All 5 Replies

Did you try:

Something<K, V>[] s = new Something<K, V>[size];

That's assuming the other class is generic, and has K and V defined. If not, you need to explicitly declare it, like so:

Something<string, int>[] s = new Something<string, int>[size];

i've tried your first line Something<K, V>[] s = new Something<K, V>[size]; but i got an error: Thing.java:15: generic array creation

this is created inside a class that has K and V defined, I think: public class Thing<K, V>...

Can you post a small complete program that shows what you are trying to do?

Also post the full text of the error messages you ae getting.

Becuase of the way generics were implemented via erasure, creating a new object using the generic type cannot be done in the obvious way that anyone would like to do it. It's not good, but it is what it is. This link has a good discussion of the various ways you can get round it.

i figured it out..
Something<K, V>[] s = (Something<K, V>[]) new Something [size];

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.