equals

A Java tuple class (Tuple2 or Pair, if you prefer)

After working with Scala for a long time, I had to come back to Java for a while to work on an Android app. Right away I missed a lot of things from the Scala world, including all of the built-in Scala collection methods, and other things as simple as the Scala Tuple classes.

If you haven’t used them before, a Scala Tuple class lets you write code like this:

Tuple<String, Integer> t = new Tuple<>("age", 41);

If you’re comfortable with generics, the Java implementation of a Tuple class like this is simple:

How to define an equals method (object equality) in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 4.15, “How to define an equals method (object equality) in Scala.”

Problem

You want to define an equals method for a Scala class so you can compare object instances to each other.

Scala - How to find the unique items in a List, Array, Vector (sequence)

Scala FAQ: How do I find the unique items in a List, Array, Vector, or other Scala sequence?

Solution: Use the distinct method.

Here's a simple example using a List of integers:

scala> val x = List(1,1,1,2,2,3,3)
x: List[Int] = List(1, 1, 1, 2, 2, 3, 3)

scala> x.distinct
res0: List[Int] = List(1, 2, 3)

As you can see, res0 now contains only the unique elements in the list.

How to compare String equality in Java

Java String comparison FAQ: Can you share some examples of how to compare strings in Java?

If you’re like me, when I first started using Java, I wanted to use the == operator to test whether two String instances were equal, but that’s not the correct way to do it in Java.

In Scala you compare Strings with '==', not 'equals'

Scala String FAQ: How do you compare string equality in Scala?

In Scala you compare two Strings with the == operator. This is different than Java, where you compare two Strings with the equals method.

For example, given these strings:

A Java instanceof array example alvin September 20, 2009 - 12:00am

While working with various "Java instanceof" tests recently, my curiosity was piqued, and I thought I'd take a look at how the instanceof operator works when testing against a Java array.

A Java “instanceof null” example

You might think that when the Java instanceof operator is used to test a null reference, such as a null reference to a String, instanceof would realize that even though the reference is currently null, it is a reference to a String, so you might expect instanceof to return true ... but it doesn't.

Perl comparison operators

Perl equality FAQ: Can you share a list of the Perl equality operators?

Sure. Here's a convenient list of the Perl comparison operators (also known as Perl equality operators, equal, or not equal operators).

The Perl comparison operators are different for numeric and string comparison tests, as you can see in the following table: