如何将映射值分配给本地类变量

时间:2018-09-19 02:18:36

标签: variable-assignment

我有一个“ ItemCount”类,其中声明了计数变量,并且初始值为0。一旦执行了地图函数,就将对地图值进行计数,并且我试图将计数的地图值分配给计数变量。但是此Count变量始终设置为0。我尝试使用SetCount但仍保留为0。请告知

public class ItemCount extends Thread
{
    String itemName;
    List<String> itemList = new ArrayList<>();
    Integer count =0;
    Map<String,Integer> map = new HashMap<String, Integer>();

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public ItemCount(String itemName,List<String> itemList){
        this.itemName = itemName;
        this.itemList=itemList;
    }

    public ItemCount()
    {

    }

    public void run(){

        for(String item : this.itemList)
        {
            if(map.containsKey(item))
            {
                    int newcount = map.get(item);
                    map.put(item, newcount+1);
            }

            else
            {

            map.put(item, 1);

             }
        }

        for(Map.Entry<String,Integer> entry : map.entrySet())
        {
            this.count = entry.getValue();
        }



    }

}

我需要在Main class中打印此计数值 *

for(ItemCount i:threadList){
            System.out.format("%-15s %-15s\n",i.itemName,i.count);
        }

Input & Output:
Enter the number of purchases
4
Enter the items purchased
red
green
red
black
Number of items to search
1
red
Item Name       Count          
red             1 (**** Count has to be 2)

*

0 个答案:

没有答案