#java

List.remove() oddities

From reddit’s r/java, a user observed that List.remove(Object) removes the first object whose equals() method returns true. Thus, if two objects have object equality with each other, but you wish to remove the second, you’re going to have to find it and return it with the indexed version of remove(int) instead of the remove(Object) call.yawkat observed that you can use Collection.removeIf() (which List inherits) and get...

1 minute(s) read

What you want to have to develop Java

Recently a user asked what they would need to know to develop a “small web application” using Java, including a database. This is not a good question, really, but IRC user surial gave a lot of relevant information that’s worth preserving and adding to. This is not what surial said – if you’re interested in the actual content, see the channel logs – but this is a paraphrase that attempts to build on surial’s...

6 minute(s) read

First steps: Structure of your first source file

This is what a class file ought to look like when you take your first steps writing java programs: public class YourAppNameHere { public static void main(String[] args) { new YourAppNameHere().go(); } private String iAmAField; void go() { System.out.println("Your code goes here!"); } void someOtherMethod() { // You can call this method from 'go' with: someOtherMethod() iAmAField = "Hello, World!"; } } In particular, copy/paste the main() method verbatim and don’t touch it. If you need access to...

2 minute(s) read

Use exceptions correctly

In this article we are going to address the common misuse of exceptions, more specifically those times when programmers fail to correctly propagate exceptions. Along the way, and most of this article, we will talk about the differences between runtime and checked exceptions and the ways in which it is appropriate to use them. Runtime exceptions There are two main differences between checked, or “normal,” exceptions, and runtime exceptions: Runtime exceptions don’t have to...

6 minute(s) read

Collapsing multiple ints into a long

Every now and then, you may want to collapse multiple values into a long, to use as a key for a Map, for example. The following code is an example of collapsing three ints into one long. Obvious care should be taken here: three ints don’t actually fit into one long, so the excess bits are just discarded. If we do this, we can afford to use the lowest 20 bits, plus the sign...

2 minute(s) read