147

I was reading through some JMockit examples and found this code:

final List<OrderItem> actualItems = new ArrayList<~>();

What does the tilde in the generic identifier mean? I know it's the unary bitwise NOT operator, but I don't see an operand here.

Also, I tried compiling it and got an error. Am I just missing something?

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Michael K
  • 3,297
  • 3
  • 25
  • 37

4 Answers4

175

It is just a shorthand for "same as in declaration".

Some IDEs, e.g. IntelliJ use this too.

The files on disk do not have this notation, which is only a compaction in the IDE GUI.

roottraveller
  • 7,942
  • 7
  • 60
  • 65
openCage
  • 2,735
  • 1
  • 18
  • 24
20

If there wasn't a tilde, I'd say, the code was already Java 7. Java 7 allows the diamond operator so this is/will be legal Java code:

Map<String, List<String>> map = new HashMap<>();

(but - no tilde with this syntax)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
14

In IntelliJ IDEA, the ~ here:

Set<String> associations = new LinkedHashSet<~>();

means String, which is the same as in the declaration on the left side.

Ascendant
  • 2,430
  • 3
  • 26
  • 34
2

I think that is shorthand to mean whatever the type is, in this case OrderItem.

Andrew White
  • 52,720
  • 19
  • 113
  • 137