简体   繁体   中英

how do I add objects of different types to a hashmap in Android?

I am trying to add various records to be added/retrieved by a single Key value.

Each data record should have the following parameters;

public class WebRecord {
        Integer UniqueCustomerID;
        Integer Count; // Number of websites for a given customer

//Repeat the following 'Count' number of times
       { // Each Record for a given Website for the same customer
    String BusinessName, Websites, siteTag;
    Integer uniqueWebID, BusinessTypeID;
       }

}

I want such records to exist based on count value I get from a Web service. I was going to use Hashmap as below:

Can someone tell me how to implement that data structure in a HASHMAP? I want to put and get these records using a single key value UniqueCustomerID;

Not good with java concepts but I think you can do,

     class WebRecord{ 
          int UniqueCustomerID; 
          int Count;
     } 

     class ContactRecord{ 
        String BusinessName, Websites, siteTag; 
        int uniqueWebID, BusinessTypeID; 
    } 

And in your java file

   MyActivity{ 
            public Map<WebRecord,ArrayList<ContactRecord>> map=new HashMap<WebRecord,ArrayList<ContactRecord>>(); 

        //now create one object of web record

        //create arraylist of ContactRecord depending upon "count" variable's value

        // fill the above both and put into map

            map.put(webRec, arrContact); 
     } 

If you have a number of ContactRecord objects equal to the Count value then you don't need to store that value explicitly.

Given your data structure above you could do.

public HashMap<Integer, ArrayList<ContactRecord>> map;

Where the key to the map is the UniqueCustomerID . To discover the Count value you can interrogate the list in the map like this.

map.get(customerId).size();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM