I’m trying to make it working for quite some time,but just can’t seem to get it. I have object Tower built of Block’s. I’ve already made it working using arrays, but I wanted to learn Set’s. I’d like to get similar functionality to this:
public class Tower {
public Tower(){
}
public Tower add(Block k1){
//(...)
//if block already in tower, return "Block already in tower"
}
public Tower delete(Block k1){
//(...)
//if block already dleted, show "No such block in tower"
}
}
Someone gave me some code, but I constantly get errors when trying to use it :
Set<Block> tower = new HashSet<Block>();
boolean added = tower.add( k1 );
if( added ) {
System.out.println("Added 1 block.");
} else {
System.out.println("Tower already contains this block.");
}
How to implement it ?
The first thing you need to study is the
java.util.SetAPI.Here’s a small example of how to use its methods:
Once you’re familiar with the API, you can use it to contain more interesting objects. If you haven’t familiarized yourself with the
equalsandhashCodecontract, already, now is a good time to start.In a nutshell:
@Overrideboth or none; never just one. (very important, because it must satisfied property:a.equals(b) == true --> a.hashCode() == b.hashCode()boolean equals(Thing other)instead; this is not a proper@Override.x, y, z,equalsmust be:x.equals(x).x.equals(y)if and only ify.equals(x)x.equals(y) && y.equals(z), thenx.equals(z)x.equals(y)must not change unless the objects have mutatedx.equals(null) == falsehashCodeis:equals: ifx.equals(y), thenx.hashCode() == y.hashCode()equalsandhashCode.Next, you may want to impose an ordering of your objects. You can do this by making your type implements
Comparable, or by providing a separateComparator.Having either makes it easy to sort your objects (
Arrays.sort,Collections.sort(List)). It also allows you to useSortedSet, such asTreeSet.Further readings on stackoverflow: