Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Put objects of different types into a ArrayList for a ModelCollection. Interfaces?

I want to have my models wrapped up in a ModelCollection which is mostly used for a ListView. The Collection has always the same attributes like title, totalResults (for Pagination) and it shall contain the listItem-Models in the ArrayList "items". However, these models have different types like "ModelCategory" or "ModelChain" and often have different Properties and Methods.

How can I achieve this in java with strong Typing discipline? I heart interface a the right way to do this. WHERE do I have to implement them?

public class ModelCollection {

              public ArrayList< ModelCategory OR ModelChain OR ModelXyz> items = new ArrayList<ModelCategory OR ModelChain OR ModelXyz>();

              private String id;
              private String title;
              private Long updated;

              private String linkSelf;
              private int totalResults;
              private int startIndex;

    /*
     more stuff like parsing a feed
    */

    }
like image 210
OneWorld Avatar asked Sep 14 '10 08:09

OneWorld


People also ask

How do you create an ArrayList of different objects in Java?

We can use the Object class to declare our ArrayList using the syntax mentioned below. ArrayList<Object> list = new ArrayList<Object>(); The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.

Can we add different data types in ArrayList in Java?

The ArrayList class implements a growable array of objects. ArrayList cannot hold primitive data types such as int, double, char, and long.

Can we store multiple data types in ArrayList?

Unlike simple arrays, an ArrayList can hold data of multiple data types. It permits all elements, including null . Elements in the ArrayList are accessed via an integer index. Indexes are zero-based.

How do you add multiple elements to an ArrayList?

Inserting multiple elements from another Collection If we have a Collection and we need to add all its elements to another ArrayList, then the addAll(Collection c) method can be used. This method will add all the elements at the end of the ArrayList.


3 Answers

Make your ModelCategory, ModelChain, and ModelXyz implement an interface. Then have your collection be on that interface.

For instance:

public interface MyModel {
}

public class ModelCategory implements MyModel {
}

List<MyModel> list = new ArrayList<MyModel>();

To reference specific methods of each class, you will need to cast your list objects to the correct type.

List<MyModel> list = new ArrayList<MyModel>();
list.add(new ModelCategory());

ModelCategory model = (ModelCategory) list.elementAt(0);

Obviously, you can use whatever methods you need to iterate through your collections.

like image 72
Tauren Avatar answered Oct 11 '22 15:10

Tauren


Solution of Tauren is correct, but remember to check instanceof like deadsven proposed, and the result is like:

    List<MyModel> list = new ArrayList<MyModel>();
    list.add(new ModelCategory());

    for(MyModel mymodelListElement: list) {
        //mymodelListElement.sameMyModelMethods()

        if(ModelCategory instanceof mymodelListElement) {
            ModelCategory modelCategoryElement = (ModelCategory)mymodelListElement;
        } else if(ModelChain  instanceof mymodelListElement) {
            ModelChain  modelChainElement = (ModelChain )mymodelListElement;
        } else if(ModelXyz instanceof mymodelListElement) {
            ModelXyz modelXyzElement = (ModelXyz)mymodelListElement;
        } else {
            //ignore
            //or
            //throw new RuntimeException("Wrong MyModel implementation")
        }

    }
like image 33
Jan Wegner Avatar answered Oct 11 '22 13:10

Jan Wegner


Define a common interface for all your model classes which gives access to the properties they share.

public interface MooModel
  String getTitle();
  // etc

And define the List<MooModel>

like image 40
willcodejavaforfood Avatar answered Oct 11 '22 15:10

willcodejavaforfood