java - Convert ArrayList to ArrayList -


I have three sections: Blob, Food and Predator, all of which are sub-classes of intangible class organisms.

I have an array list for each class: Blobs, Foods and Predators

I am writing a function that when choosing a 'target' for an organism Depending on how it is, the organism is passed as a parameter and then a suitable target is chosen - if the blob is passed then it should target a food, if a predator passes then Her blob Should be targeted, and if any food has passed it should be targeted Predator. I have now:

  ArrayList & lt; Food & gt; Foods = new array list & lt; Food & gt; (); ArrayList & LT; Blob & gt; blobs = new arreelist & lt; Blob & gt; (); ArrayList & LT; Predator & gt; Hunter = new arreelist & lt; Predetator & gt; (); Public biology concept (OBZIMUM O) {Array List & Lt; Living & gt; Search = New Arrestist & lt; Living & gt; (); If (ogateclass () == blob class) {search = food; } And if (ogateclass () == predet. Class) {search = blobs; } And if (ogateclass () == food.class) {search = hunter; } Creating goals = search.get (0); For (organ content: search) {// accessories to choose a target from a fixed search location} return target; }   

So this idea is to point to a normal Ornism Arrayist here, then specify one of the existing array lists to specify what the parameter is. That array list will then be searched for the most appropriate target that has come back.

But I am getting a type of mismatch error when I try to specify an existing ArrayList in the search variable. For example, ArrayList & lt; Food & gt; to ArrayList & lt; Organism & gt; can not be converted to.

Does anyone know the solution to such a problem? Converting from subclass to superclass is not usually an issue, so I'm hoping that there is a solution for array list.

The fundamental issue you are facing is that the list & lt; subclass & gt; not list & lt; Superclass & gt; There is a subtype of .

The way to solve your problem is to declare the variable by using the normal bound :

  list & lt;? Organic & GT; Search;   

Then it will compile:

  search = food;   

announcement list & lt;? Organic and Expanded; means "Elements of an unknown type which is subtype of the organism" in the code, elements of such a list are known for at least one organism, but the exact type is unknown.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -