Sign in to follow this  

[java] Generic Class Type Erasure

This topic is 4549 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm working on a generic class that stores a 2D array of something. This is what I have:
[source="java"]
public class HexArray<E> {
   private E[][] grid;
    
   public HexArray(int row, int col) {
      grid = (E[][])new Object[row][col];
   }
}

However, I get a warning (this is in Eclipse) at the constructor where I initialize the grid array saying "Type safety: The cast from Object[][] to E[][] is actually checking against the erased type Object[][]." Another forum I asked at brought up something about "type erasure." I only have a little experience with generics, so I'm not sure I've wrapped my head around that. What I'm asking now is whether or not my grid is still an E array and not an Object array. Thanks.

Share this post


Link to post
Share on other sites
shouldn't it just be:
public class HexArray<E> {
private E[][] grid;

public HexArray(int row, int col) {
grid = new E[row][col];
}
}

edit: ok, obviously not :) Shows what I know about Java's generics!
edit 2: what you could do is pass a reference to an E[][] in the constructor. i.e.
public class HexArray<E> {
private E[][] grid;

public HexArray(E[][] grid) {
this.grid = grid;
}
}

Share this post


Link to post
Share on other sites
If you want to understand more about erasure, you might want to look at Bruce Eckel's old blog. He has a series of articles "Puzzling Through Erasure" in four parts.

Share this post


Link to post
Share on other sites
I read those articles on Eckel's blog, and I've started to loose hope. I think for now I'll just forget about making my class able to contain multiple classes, and just have it store objects of the class I planned on storing in it. Thanks for the link though SiCrane.

Share this post


Link to post
Share on other sites

This topic is 4549 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this