java - trouble returning an object, Bin, through a method. Needs to "Cast" or change to Object -


i'm beginner trying learn java!

i trying out book building skills in object-oriented design, , working on roulette.

i have class, bin, constructs treeset contains outcome-objects. constructed in outcome class.

now, working on wheel class, , here using new vector(38) i'm filling 38 new bin() s.

now, issue.

i want create method retrieves bin-object vector.

bin get(int bin){     return  bins.elementat(bin); } 

this doesn't work , eclipse suggesting 2 fixes:

1: add cast

2: change bin object

what going on here? why can't return bin way want to? when cast or change object, doesn't work.

this outcome class

this bin class

this wheel class

package roulette;  import java.util.random; import java.util.vector;  public class wheel {  vector bins; random rng;   wheel(random rng){     rng =  new random();      bins = new vector(38);     (int i=0; i<38; i++){         bins.add(i, new bin());     } }  void addoutcome(int bin, outcome outcome){     this.bins.elementat(bin).add(outcome); }  bin next(){     int rand = rng.nextint(38);      return bins.elementat(rand);  }  bin get(int bin){     return  bins.elementat(bin); }  } 

the compiler not know @ runtime out of bins.elementat(). since have not defined type, expects object of class (an object instance), may or may not of class bin.

so, have (for compiler) like

  object = new bin();   bin b = a; 

since compiler not sure, needs cast ensure return appropiated type (or fail if there cast error). anyway, must explicit that

  object = new bin();   bin b = (bin) a;    // compiles , works    object = new string("hello world");   bin b = (bin) a;    // compiles fails @ runtime classcastexception. 

the alternative using generics specify vector contain bin instances

  vector<bin> bins = new vector<bin>(); 

that way compiler sure bins.getelement() returns bin object.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -