How to store multiple datatypes in an array?

后端 未结 3 1602
一向
一向 2021-01-02 05:48

I\'m looking for something like an Array, but it needs to store multiple data types. The Oracle Java tutorials says, \"An array is a container object that holds a fixed numb

3条回答
  •  别那么骄傲
    2021-01-02 06:22

    You can create an array of your Custom-Class.

    public class YourCustomClass {
    
         String id;
         String name;
         double longitude;
         // and many more fields ...
    
        public YourCustomClass() {  // constructor 
    
        }
    
        public void setID(String id) {
            this.id = id;
        }
    
        public String getID() {
            return id;
        }
    
        // and many more getter and setter methods ...
    }
    

    Inside your custom-class you can have as many fields as you want where you can store your data, and then use it like that:

    // with array 
    YourCustomClass [] array = new YourCustomClass[10];
    array[0] = new YourCustomClass();
    array[0].setID("yourid");
    
    String id = array[0].getID();
    
    // with arraylist
    ArrayList arraylist = new ArrayList();
    arraylist.add(new YourCustomObject());
    arraylist.get(0).setID("yourid");
    
    String id = arraylist.get(0).getID();
    

    You can also let the AsyncTasks doInBackground(...) method return your Custom-class:

    protected void onPostExecute(YourCustomClass result) {
     // do stuff...
    }
    

    Or an array:

    protected void onPostExecute(YourCustomClass [] result) {
     // do stuff...
    }
    

    Or a ArrayList:

    protected void onPostExecute(ArrayList result) {
     // do stuff...
    }
    

    Edit: Of course, you can also make a ArrayList of your custom object.

提交回复
热议问题