将元素添加到数组数组

时间:2015-03-10 13:33:05

标签: java arrays multidimensional-array colors

我有一个带颜色变量

的数组
Color [] [] bin = new Color [64] [];

之后我想在这个数组中插入颜色 循环遍历颜色列表和tmpColor是循环中的特定颜色。我需要将它插入它所属的特定循环中。

int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);
bin[idx].push(tmpColor);

然而,这似乎不起作用。如何在特定索引中的数组中添加颜色?

2 个答案:

答案 0 :(得分:0)

如果索引需要List种颜色,可以使用Map

private Map<Integer, List<Color>> bin = new HashMap<Integer, List<Color>>();

int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);

if(bin.get(idx)==null) bin.put(idx, new ArrayList<Color>());

bin.get(idx).add(tmpColor); //This should be exactly what you need

您还可以使用不同的结构,例如List<List<Color>>List<Color>[]。每个结构都在List上进行中继,因为List可以在不知道初始长度的情况下进行更新和创建。

我要做的是为color bin和一些有用的方法创建一个单独的类:

public class Bin{

    private List<Color> colors = new ArrayList<Color>();

    public void addColor(Color col){
        this.colors.add(col);
    }

    public List<Color> getColors(){
        return this.colors;
    }

    public boolean hasColor(Color col){
        return colors.contains(col);
    }
    //and so on...
}

现在,您目标的最佳结构是具有延迟初始化的地图:

private Map<Integer, Bin> myBinsOfColors = new HashMap<Integer, Bin>();

int idx = 16* (tmpColor.getRed()/64) + 4*(tmpColor.getGreen()/64) + (tmpColor.getBlue()/64);

if(myBinsOfColors.get(idx)==null) myBinsOfColors.put(idx, new Bin()); //Lazy

myBinsOfColors.get(idx).addColor(tmpColor); //This should be exactly what you need

要获得avarage和颜色数量,您可以在Bin类中实现两种方法:

public class Bin{

    private List<Color> colors = new ArrayList<Color>();

    //As above.
    public Color calculateAverage() {
       Integer red = 0;
       Integer blue = 0;
       Integer green = 0;
       if(!colors.isEmpty()) {
         for (Color col : colors) {
            red+= col.getRed();
            green+= col.getGreen();
            blue+= col.getBlue();
         }

         return new Color(red/colors.size(), green/colors.size(), blue/colors.size());
       }
       return null;
    }

    public int getColorCount(){
        return this.colors.size();
    }

    //and so on...
}

答案 1 :(得分:0)

我如何解决以下问题:而不是创建我创建的数组数组和ArrayLists数组

int size = 64;
ArrayList<Color>[] lists = new ArrayList[size];
for( int i = 0; i < size; i++) {
    lists[i] = new ArrayList<Color>();
}

之后我将元素推送到特定的bin(在本例中为列表)

lists[idx].add(tmpColor);

然后获得长度和数组中的第一种颜色如下:

for (ArrayList<Color> p : lists){
    System.out.println("size of bin" + p.size());
    if (p.isEmpty())
        continue;
    else {
    System.out.println("list" + p.get(0));
    }
}
相关问题