Why does this list have duplicates?

I'm using a HashSet and I implemented a hashCode method. Yet still the list is full of duplicates. I don't get it.

import java.util.HashSet;


HashSet<State> states = new HashSet<State>();
ArrayList<State> states_arr = new ArrayList<State>();

State s;

int index = 0;

void setup() {
  size(600, 600);

  // create a lot:
  for (int i = 0; i < 1000; i++) {

    // randomSeed 1 for now so there all the same
    // which should in theory only add 1
    randomSeed(1);
    s = new State();
    if (!states.contains(s)) {
      states.add(s);
      states_arr.add(s);
    }
  }

  println(states.contains(s));
  randomSeed(1); 
  println(states.contains(new State()));

  println(states_arr.size());


}

void draw() {
  background(255);

  float cw = width / 3;
  float ch = height / 3;

  int i = 0;  
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 3; x++) {


      if (s.cells[i]) {
        float px = x * cw;
        float py = y * ch;
        fill(255, 0, 0);
        rect(px, py, cw, ch);
      }

      i++;
    }
  }
}


void keyPressed() {
  println(index);
   s = states_arr.get(index++); 
}


class State {

  boolean[] cells = new boolean[9];

  State () {
    cells[0] = random(1) < 0.5;
    cells[1] = random(1) < 0.5;
    cells[2] = random(1) < 0.5;
    cells[3] = random(1) < 0.5;
    cells[4] = true;
    cells[5] = random(1) < 0.5;
    cells[6] = random(1) < 0.5;
    cells[7] = random(1) < 0.5;
    cells[8] = random(1) < 0.5;
  }

  int hashCode() {
    //println("hashCode");
    int hash = 0;
    hash |= cells[0] ? 1 << 1 : 0;
    hash |= cells[1] ? 1 << 2 : 0;
    hash |= cells[2] ? 1 << 3 : 0;
    hash |= cells[3] ? 1 << 4 : 0;
    hash |= cells[4] ? 1 << 5 : 0;
    hash |= cells[5] ? 1 << 6 : 0;
    hash |= cells[6] ? 1 << 7 : 0;
    hash |= cells[7] ? 1 << 8 : 0;
    hash |= cells[8] ? 1 << 9 : 0;
    println(hash);
    return hash;
  }
}

Answers

Sign In or Register to comment.