HashMap with multiple values under the same key

前端 未结 22 2067
旧时难觅i
旧时难觅i 2020-11-22 06:49

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to

22条回答
  •  醉梦人生
    2020-11-22 06:57

    I am so used to just doing this with a Data Dictionary in Objective C. It was harder to get a similar result in Java for Android. I ended up creating a custom class, and then just doing a hashmap of my custom class.

    public class Test1 {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addview);
    
    //create the datastring
        HashMap hm = new HashMap();
        hm.put(1, new myClass("Car", "Small", 3000));
        hm.put(2, new myClass("Truck", "Large", 4000));
        hm.put(3, new myClass("Motorcycle", "Small", 1000));
    
    //pull the datastring back for a specific item.
    //also can edit the data using the set methods.  this just shows getting it for display.
        myClass test1 = hm.get(1);
        String testitem = test1.getItem();
        int testprice = test1.getPrice();
        Log.i("Class Info Example",testitem+Integer.toString(testprice));
    }
    }
    
    //custom class.  You could make it public to use on several activities, or just include in the activity if using only here
    class myClass{
        private String item;
        private String type;
        private int price;
    
        public myClass(String itm, String ty, int pr){
            this.item = itm;
            this.price = pr;
            this.type = ty;
        }
    
        public String getItem() {
            return item;
        }
    
        public void setItem(String item) {
            this.item = item;
        }
    
        public String getType() {
            return item;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public int getPrice() {
            return price;
        }
    
        public void setPrice(int price) {
            this.price = price;
        }
    
    }
    

提交回复
热议问题