为什么Processing认为我将int传递给此代码末尾的color()函数?

时间:2011-03-15 21:38:11

标签: hashmap casting processing

前言:我正在使用Processing,我从未使用过Java。

我有这个处理功能,旨在查找并返回我正在处理的当前图像的像素中最常见的颜色。最后一行抱怨“PApplet类型中的方法color(int)不适用于参数(String)。”怎么了?

   color getModeColor() {
     HashMap colors = new HashMap();
     loadPixels();
     for (int i=0; i < pixels.length; i++) {
       if (colors.containsKey(hex(pixels[i]))) {
         colors.put(hex(pixels[i]), (Integer)colors.get(hex(pixels[i])) + 1);
       } else {
         colors.put(hex(pixels[i]),1);
       }
     }

     String highColor;
     int highColorCount = 0;

     Iterator i = colors.entrySet().iterator();
     while (i.hasNext()) {
       Map.Entry me = (Map.Entry)i.next();
       if ((Integer)me.getValue() > highColorCount) {
         highColorCount = (Integer)me.getValue();
         highColor = (String)me.getKey();
       }
     } 
     return color((highColor);
   }

我正在看的Processing docs在HashMap上非常稀疏,所以我不确定它里面发生了什么,但是我一直在用Java docs来增加它们的可用性指向。但我并不是真的想知道这些类型正在发生什么。看起来HashMap中的键需要是一个字符串,并且值必须是一个整数,但是它们作为我必须在使用前投射的对象出现。所以我不确定这是否会导致这个故障。

或者也许只有color()的问题,但the docs说它会采用十六进制值,这是我试图用作HashMap中的键(我宁愿使用它)颜色本身)。

现在我已经讨论过了,我认为color()函数将十六进制值视为int,但hex()函数将颜色转换为字符串。我似乎无法将该字符串转换为int。我想我可以解析子串并重建颜色,但必须有一些更优雅的方法来做到这一点,我错过了。我应该创建一个键值对类,它将保持颜色和计数并使用那些的arraylist?

提前感谢您提供的任何帮助或建议!

2 个答案:

答案 0 :(得分:0)

我将深入研究这一点,但最初的想法是使用Java泛型,以便编译器会抱怨类型问题(并且您不会遇到运行时错误):

HashMap<String,Integer> colors = new HashMap<String,Integer>();

因此编译器将知道键是字符串,元素是整数。因此,不需要铸造。

答案 1 :(得分:0)

我没弄清楚,但我确实解决了这个问题。我只是从颜色组件中创建自己的字符串,如:

 colors.put(red(pixels[i]) + "," + green(pixels[i]) + "," + blue(pixels[i]),1)

然后让函数像这样删除一个颜色:

     String[] colorConstituents = split(highColor, ",");
     return color(int(colorConstituents[0]), int(colorConstituents[1]), int(colorConstituents[2]));

这似乎不是处理它的最好方法 - 如果我搞这个长期的话我想我会改变它来使用一个保持颜色和数量的物体的arraylist,但是这个现在有效。