Mr. Avad
Mr. Avad

Reputation: 31

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;

Upvotes: 2

Views: 1130

Answers (2)

MKJParekh
MKJParekh

Reputation: 34301

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); 
     } 

Upvotes: 1

Louth
Louth

Reputation: 12357

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();

Upvotes: 0

Related Questions