4

In my Android project I have made an abstract AsyncTask class in which I input the URL and if needed paging information so I don't need to keep writing the HTTP stuff etc.

I've made an abstract method, onAsyncTaskResult(Object o) which must be implemented on use. However when casting it to the appropriate object (can be of different types) the IDE gives me a warning

"Unchecked cast for java.lang.Object to java.util.ArrayList<com.company.package.subpackage.MyItem>"

Here is my code snippet of the implemention of said function

new SuperCoolAsyncTask() {
      @Override
      protected void onAsyncTaskResult(Object o) {
          if(o instanceof ArrayList) {
          //generates warning in the following line
          AppConstants.scoreStatistics = (ArrayList<MyItem>)o;
      }
   }
}.execute(get_url_score_statistics());

How am i supposed to cast this to an ArrayList<MyItem> without generating a warning?

Without the <MyItem> declaration it throws an "Unchecked assignment"

Rae
  • 342
  • 6
  • 17
  • 1
    You can only cast to `ArrayList`, but not to `ArrayList`. This is because by the time the code is compiled every reference to `MyItem` is lost and replaced by a reference to `Object`. – Micha Wiedenmann Jun 24 '13 at 11:33
  • Thanks Micha, great explaination! – Rae Jun 24 '13 at 11:44

3 Answers3

5

You cannot do it without a warning. You are casting an Object to some other class, and even if the Object is an instance of ArrayList you don't know it's generic type.

Update:

if you wrote SuperCoolAsyncTask yourself, you could parametrize the class with generics:

public abstract class SuperCoolAsyncTask<ResultType> {

    protected abstract void onAsyncTaskResult(ResultType o);

}

And then, when you invoke your code:

new SuperCoolAsyncTask<ArrayList<MyItem>>() {
    @Override
    protected void onAsyncTaskResult(ArrayList<MyItem> o) {
            AppConstants.scoreStatistics = o;
    }
}.execute(get_url_score_statistics());
darijan
  • 9,725
  • 25
  • 38
3

You can't avoid the warning, but you can hide it with a @SuppressWarnings annotation. Try this:

new SuperCoolAsyncTask() {
      @Override
      @SuppressWarnings("unchecked")
      protected void onAsyncTaskResult(Object o) {
          if(o instanceof ArrayList) {
          //generates warning in the following line
          AppConstants.scoreStatistics = (ArrayList<MyItem>)o;
      }
   }
}.execute(get_url_score_statistics());

The other option, if you're really worried about type safety, is to leave the generic unspecified (i.e. only cast to ArrayList, not ArrayList, and then cast each element as you remove it.

Martin Wickham
  • 442
  • 4
  • 9
0

You can cast your object to ArrayList. you can't cast it to your type

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115