Tuesday, May 25, 2010

Set interface to prevent duplicating items

package test;
import java.util.*;

class Vertex {
int number;

public Vertex(int number) {
this.number = number;
}

public String toString() {
return number + "";
}

@Override
public boolean equals(Object obj) {
return this.number == ((Vertex) obj).number;
}

}

public class SetTest {
public static void main(String[] args) {
Set vertices = new HashSet();

Vertex a = new Vertex(2);
Vertex b = new Vertex(3);
Vertex c = new Vertex(3);

System.out.println(b.equals(c));

vertices.add(a);
vertices.add(b);
vertices.add(c);

System.out.println(vertices);
}
}


Class HashSet
Interface Set
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Equals method is overriden but it doesn't work!
true
[3, 2, 3]


groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/5abcb183daa74336#

0 komentarze:

Post a Comment