I recently searched for a lot of code (for my own good, as I am still involved in the program), and I noticed a number of Java projects (from what seem to be respected programmers) in which they use some kind of direct casting down.
I actually have a few examples, but here is the one that I pulled directly from the code:
public Set<Coordinates> neighboringCoordinates() { HashSet<Coordinates> neighbors = new HashSet<Coordinates>(); neighbors.add(getNorthWest()); neighbors.add(getNorth()); neighbors.add(getNorthEast()); neighbors.add(getWest()); neighbors.add(getEast()); neighbors.add(getSouthEast()); neighbors.add(getSouth()); neighbors.add(getSouthWest()); return neighbors; }
And from the same project, here is another (possibly shorter) example:
private Set<Coordinates> liveCellCoordinates = new HashSet<Coordinates>();
In the first example, you can see that the method has a return type of Set<Coordinates>
- however, this particular method will always return only a HashSet
- and no other type of Set
.
In the second example, liveCellCoordinates
initially defined as Set<Coordinates>
, but immediately turns into a HashSet
.
And this is not only this single, specific project - I found that this takes place in several projects.
I'm curious what logic is behind this? Are there some code conventions that would consider this good practice? Does this make the program faster or more efficient? What is the use of this?
source share