I've tried the following line:
Map<Character, Color> map={new Character('r'):Color.red,new Character('b'):Color.black};
But Netbeans 7 rejects this, with the error message '{' expected, ';' expected
.
I've set the Source/Binary format as 'JDK 7'and the platform to 'JDK 1.7', is there anything else I need to do?
A collection literal is a syntactic expression that evaluates to an array, List , Map , or other aggregate type.
Single quote: Java literal is specified to a char data type as a single character enclosed in a single quote. For example, char ch = 'a'; Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char.
// The hexa-decimal number should be prefix // with 0X or 0x. int x = 0X123Face; Binary literals: From 1.7 onward, we can specify literal value even in binary form also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
Literals provide a means of expressing specific values in your program. For example, in the following statement, an integer variable named count is declared and assigned an integer value. The literal 0 represents, naturally enough, the value zero.
Neither Java 7 nor Java 8 supports collection literals, as discussed in this question: Are Project Coin's collection enhancements going to be in JDK8?
You can use Google's Guava library if you need only immutable collections. ImmutableList
, ImmutableSet
and ImmutableMap
have several overloaded factory methods or even builders that make creating collections easy:
List<Integer> list = ImmutableList.of(1, 1, 2, 3, 5, 8, 13, 21); Set<String> set = ImmutableSet.of("foo", "bar", "baz", "batman"); Map<Integer, String> map = ImmutableMap.of(1, "one", 2, "two", 3, "three");
EDIT
Java 9 has added collection factory methods similar to those of Guava:
List.of(a, b, c); Set.of(d, e, f, g); Map.of(k1, v1, k2, v2) Map.ofEntries( entry(k1, v1), entry(k2, v2), entry(k3, v3), // ... entry(kn, vn) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With