Type Safety: Cast from Object to E


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Type Safety: Cast from Object to E

  1. #1
    Join Date
    Apr 2005
    Posts
    18

    Question Type Safety: Cast from Object to E

    I've been working in Eclipse on a class that holds a collection of objects in a 2D array. To enable generic types, I make casts between Object and E when initializing my array in my constructor:
    Code:
    class HexArray<E> {
    
    private E[][] grid;
    
    public HexArray(int rowSize, int colSize) {
    
    grid = (E[][])new Object[row][col];
    
    ...
    }
    ...
    }
    The thing is I get a warning when I initialize my grid array saying "Type safety: The cast from Object[][] to E[][] is actually checking against the erased type Object[][]." It's not an error; just an Eclipse warning. Should I worry/care about this?

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    Arrays in Java are weird, there is no association between subclasses in arrays. For instance:
    Code:
    Object[] objs = new String[5];
    is not valid. When Java implements generics they do something called "type erasure" that means they basically change all of your Es to Objects after the typing has been done. So I would guess that this warning is meaning something like: "You are casting Object[][] to Object[][], this doesn't do anything at all!" So, basically I would say that since it is just a warning you can probably safely ignore it. If you are worried about it, you can convert to something that gives a bit more type safety like Lists or Vectors or whatever.

    Hope this helps.
    ~evlich

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center