0

so let's say i want to write somthing like an ArrayList just not a list but an ArrayGrid (2 dimensional versioon)

I already figured out that ArrayList uses an Object[] to store data.

so i made an

private Object[][] grid;

but my getData method throws a ClassCastException:

public E[][] getData(){
    return (E[][]) grid;
}

The above method and this one:

public E get(int x, int y){
    return (E) grid[x][y];
}

both are giving me a warning: "Type safety: Unchecked cast from Object to E"

I can imagine why, but i can't seen to find a solution. So how does ArrayList do that?

Filburt
  • 17,626
  • 12
  • 64
  • 115
PH-zero
  • 293
  • 1
  • 4
  • 15
  • if you look at the source of `ArrayList`, it suppresses the warning – hsluo Apr 05 '14 at 14:56
  • The important thing here is the ClassCastException, not that warning. Look at my answer for more details (http://stackoverflow.com/questions/22882338/how-to-write-a-public-class-myliste/22883431#22883431) – tzima Apr 05 '14 at 16:27

1 Answers1

1

Here the ArrayList.java file if it could help.

EDIT : this is the portion you are looking for :

        @SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}


/**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    rangeCheck(index);


    return elementData(index);
}

EDIT :correcion But if you use generic type you can do like this instead of using object:

    private E[][] grid; //seems to be impossible
user43968
  • 2,049
  • 20
  • 37