0

im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing" error when running the following code

public class Test1
{
  public static void main(String args[])
  {
    Thing whipersnaper = new Thing(30, "whipersnaper"); 
    List storage = new List();

    storage.insert(whipersnaper);

    Thing x = storage.getItem(0);

    x.doubleWeight();

    System.out.println(x.getWeight());
  }
}

here is the "Thing" class

public class Thing
{
  private int weight;
  private String name;

  public Thing(int weight,String name){
    this.weight = weight;
    this.name = name;
  }


  public void doubleWeight(){
    this.weight *= 2;
  }

  public int getWeight(){
    return this.weight;
  }
}

finally here is the List class

public class List
{
  private Object[] itemList;
  private int size;

  public List()
  {
    this.itemList = new Object[10];
    this.size = 0;
  }

  public void insert(Object item){
    itemList[size] = item;
    size++;
  }

  public Object getItem(int index){
    return itemList[index];
  }
}

i need the list to be able to hold objects of any type and not exclusively Thing objects. i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.

Mark.B
  • 31
  • 1
  • 5
  • You would need to cast it. The list holds Object objects. Once it goes in the list you don't know what it is, so you need to cast. Something like `Thing t = (Thing)storage.getItem(0);` – jack.benson Feb 18 '20 at 20:20
  • @Progman This is not a Generics question. He needs to cast, as he is not using generics at all (though a Generic List of some kind would be very useful in this instance). – jack.benson Feb 18 '20 at 20:22
  • I agree with @Progman, generics is the solution here. And if not then change List to take Thing instead of object – Joakim Danielson Feb 18 '20 at 20:23
  • You're getting compiler warnings. Pay attention to them. – chrylis -cautiouslyoptimistic- Feb 18 '20 at 20:23
  • Why closing this question? It is not related to generics, but rather explicit casting. – jpact Feb 18 '20 at 20:38
  • @jpact Because generics were invented _specifically_ to solve this problem. – chrylis -cautiouslyoptimistic- Feb 18 '20 at 20:49
  • @chrylis-onstrike- I completely agree with you, that generics were invented to solve this. But, maybe further explanation to "asker" of this question could be useful. I.e, why exception was thrown, why explicit casting is required in this case (assigning superclass (Object) to subclass (Thing)), difference between implicit and explicit casting, etc. – jpact Feb 18 '20 at 22:00

2 Answers2

1
Thing x = (Thing) storage.getItem(0);
Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67
1

Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);

Atahan Atay
  • 363
  • 2
  • 15