0

SimpleyArray

public class SimpleArray<T> {

    private Object[] object;
    private int index = 0;

/** * Method add() add value, defined in the instance of SimpleArray class to the array. * @param value that would be added to array. */

public void add(T value) {
    this.object[index++] = value;
}

/**
 * Method get() created to get the value from the array passing the index.
 * @param position in array, which value going to get.
 * @return value from index was passed to the method.
 */

    public T get(int position) {
        return (T) this.object[position];
    }
}
  • 1
    Possible duplicate of [Unchecked cast warning in Java](http://stackoverflow.com/questions/16334944/unchecked-cast-warning-in-java) – River May 14 '17 at 21:54
  • The definitions of any methods which add to the array are relevant. Please add them. – Andy Turner May 14 '17 at 21:56
  • My (somewhat flippant) [answer to this question](http://stackoverflow.com/questions/43172800/arraylists-instantiating-of-the-inner-t-array/43172930#43172930) is relevant here. – Andy Turner May 14 '17 at 21:57

1 Answers1

2

A warning is not an indicator of a problem, necessarily: it is where the compiler can't prove that there will be a problem, just that it thinks there might be a problem.

Provided you are only ever putting instances of T into the array - for example, your add method looks like something this:

 public void add(T element) {
   // No bounds checking etc, for clarity.
   object[index++] = element;
 }

then you know that (T) object[someIndex] is actually safe, because the only things you put into the array are instances of T (or null, which can be cast to T).

So adding @SuppressWarnings("unchecked") would then be fine here. It is a bad practice to suppress warnings as a matter of course, but it is fine where the invariants of the class (which are unknown to the compiler) mean that it is not an actual problem.

The reason for using an Object[] here is that you can't actually create an array of a non-reifiable class. But it's straightforward enough to use an Object[] and cast appropriately; after all, this is all the compiler would be doing anyway, if you were able to use a T[] directly, because of type erasure.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216