Skip to main content

TreeSet contains(obj) doe not behave as expected

Please note these forums are being decommissioned and use the new and improved forums at
No replies
Joined: 2013-07-20


I am using the class TreeSet from the java collections library and I have a little problem with the "contains(Object)" method.
I want to use the TreeSet to order a number of Layer-Objects by their Z-Coordinate in a little project of mine.
Sometimes the Z-Coordinate of a layer can change, in that case I
1). remove it from the set
2). change its Z-value
3). add it to the set again
However, my problem is that sometimes a Layer that was added to the set can not be removed anymore since the set doesnt notice, that the Layer is contained within the set.

This is how I construct the TreeSet:

	private final TreeSet<Layer> allLayers = new TreeSet<>(new Comparator<Layer>() {<br />
		public int compare(Layer o1, Layer o2) {<br />
			if (o1.equals(o2)) {<br />
				return 0;<br />
			}<br />
			if (o1.get_z() >= o2.get_z()) {<br />
				return 1;<br />
			}<br />
			return -1;<br />
		}<br />

For adding and removing I just use the standard functions "add(Object)" and "remove(Object)".

I have build a little help function to test this behaviour:

	public void containsTest(Layer layer) {<br />
		for (Layer a : allLayers) {<br />
			if (a.equals(layer)) {<br />
				System.out.println(layer+" is contained.");<br />
			}<br />
		}<br />
		System.out.println("Contains " + layer + " = " + allLayers.contains(layer));<br />

The outcome of this is sometimes:
Layer(0) is contained
Contains Layer(0) = false

If I use this class incorrectly please tell me so. Thanks in advance.