After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?
-
17Note that it's not always a great idea to use these hidden features; often times they are surprising and confusing to others reading your code.– Kevin BourrillionNov 5, 2009 at 18:10
-
1You (/someone) should probabbly sum up the answers neatly in the question body like the C# question.– ripper234Dec 10, 2009 at 19:34
100 Answers
Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.
ThreadLocals are typically not so widely known as a way to store per-thread state.
Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.
-
40Double-brace initialization... weird... I'd be wary of adopting that particular idiom too widely though, since it actually creates an anonymous subclass of the object, which could cause confusing equals/hashcode problems. java.util.concurrent is a truly great package.– MB.Sep 17, 2008 at 12:02
-
6I have taught Java, and this is the very first time I've come across this syntax... which goes to show you never stop learning =8-)– YuvalSep 23, 2008 at 8:48
-
49Note that if you retain a reference to a collection initialized with this "double brace" idiom (or if we call it by its real name - annonymous class with initializer block), you implicitly hold a reference to the outer object which can cause nasty memory leaks. I'd recommend avoiding it altogether. Oct 5, 2008 at 13:05
-
51"Double-brace initialization" is a very euphemistic name for creating an anonymous inner class, glossing over what's really happening and making it sound as if inner classes were intended to be used this way. This is a pattern I'd prefer remain hidden.– ericksonOct 23, 2008 at 14:27
-
11Almost, it is not really a static block but an "initializer block" which is different since it gets executed at a different time (see the link I put in the answer for more details) Mar 11, 2009 at 9:49
Joint union in type parameter variance:
public class Baz<T extends Foo & Bar> {}
For example, if you wanted to take a parameter that's both Comparable and a Collection:
public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}
This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.
-
My favourite use for this is when you need a method that accepts an Appendable Charsequence. Apr 20, 2009 at 3:51
-
5
-
9@Grasper: No, OR (disjoint union) is not provided in that context. But you can use a disjoint union datatype like Either<A, B> instead. This type is the dual of a Pair<A, B> type. Look at the Functional Java library or the Scala core libraries for an example of such a datatype. Jun 16, 2009 at 21:51
-
5You should said that you MUST extends only one class and several interfaces -> public class Baz<T extends Clazz & Interface1 & InterfaceI... and not class Baz<T extends Clazz1 & ClazzI> Oct 17, 2011 at 8:53
I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :
public class App {
public App(String name) { System.out.println(name + "'s constructor called"); }
static { System.out.println("static initializer called"); }
{ System.out.println("instance initializer called"); }
static { System.out.println("static initializer2 called"); }
{ System.out.println("instance initializer2 called"); }
public static void main( String[] args ) {
new App("one");
new App("two");
}
}
Executing the main
method will display:
static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called
I guess these would be useful if you had multiple constructors and needed common code
They also provide syntactic sugar for initializing your classes:
List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};
Map<String,String> codes = new HashMap<String,String>(){{
put("1","one");
put("2","two");
}};
-
38The advantage of this over an explicit method that needs to be called is that if someone adds a constructor later they don't need to remember to call init(); that will be done automatically. This can prevent errors by future programmers. Oct 10, 2008 at 15:45
-
40
-
2What if you extend the class and instantiate various children? Will it still behave in the same manner? Jan 27, 2009 at 12:48
-
12People often dis certifications (e.g. stackoverflow.com/questions/281100/281127#281127) and especially question their technical merits. But if more programmers here had studied for their SCJP, this would not be considered a "hidden feature" by so many. ;-)– JonikApr 21, 2009 at 8:46
-
12I bet even "java in 24 hours" book has this "obvious feature". read more guys :)(– ÖzgürMay 6, 2009 at 19:40
JDK 1.6_07+ contains an app called VisualVM (bin/jvisualvm.exe) that is a nice GUI on top of many of the tools. It seems more comprehensive than JConsole.
-
And it has a plugin (it is an netbeans thingie) that allows it to use Jconsole plugins. Quite nice. May 26, 2009 at 7:54
-
VisualVM is the best thing since sliced bread, really! Too bad it doesn't have all the features when running against JDK 1.5– sandosFeb 17, 2010 at 12:26
-
I find VisualVM slow or unusable in some circumstances. The commercial YourKit does not have this problem, but is unfortunately not free.– RoaltSep 23, 2010 at 11:33
-
The more recent versions of Visual VM, from JDK 1.6.0_22 and later, are much improved. I would bet JDK1.7 has an even better version of it. Aug 24, 2011 at 20:40
Classpath wild cards since Java 6.
java -classpath ./lib/* so.Main
Instead of
java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main
See http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:
// code goes here
getmeout:{
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
for (int k = j; k < N; ++k) {
//do something here
break getmeout;
}
}
}
}
Who said goto
in java is just a keyword? :)
-
2Well, I would rather prefer to have an option to do it several ways. For example, I saw people using System.exit(1); in Servlet and EJB code, but that does not mean that we should remove System.exit(); from the JDK, right? Sep 8, 2008 at 10:25
-
31Under some circumstances, within a nested loop construct, it can be useful to continue to the next iteration of an outer loop. This would be a reasonable use of this feature. Nov 8, 2008 at 18:57
-
75What's especially unknown to many programmers (and probably just as well) is that you can actually label and break out of ANY old block. It doesn't have to be a loop-- you can just define some arbitrary block, give it a label, and use break with it. Apr 20, 2009 at 4:10
-
27It is not a goto at all, it can only return to a prior iteration (ie: you cannot jump forward). This is the same mechanism that occurs when an iteration returns false. Saying java has goto is like saying any language whose compiler produces a JUMP instruction has a goto statement.– ZombiesOct 1, 2009 at 13:38
-
4So you interview based on Java trivia rather than on aptitude to solve problems and think through designs. I'll make sure I never interview with your company. :) Aug 24, 2010 at 20:35
How about covariant return types which have been in place since JDK 1.5? It is pretty poorly publicised, as it is an unsexy addition, but as I understand it, is absolutely necessary for generics to work.
Essentially, the compiler now allows a subclass to narrow the return type of an overridden method to be a subclass of the original method's return type. So this is allowed:
class Souper {
Collection<String> values() {
...
}
}
class ThreadSafeSortedSub extends Souper {
@Override
ConcurrentSkipListSet<String> values() {
...
}
}
You can call the subclass's values
method and obtain a sorted thread safe Set
of String
s without having to down cast to the ConcurrentSkipListSet
.
-
-
24I use this a lot. clone() is a great example. It's supposed to return Object, which means you'd have to say e.g. (List)list.clone(). However if you declare as List clone(){...}, then the cast is unnecessary. Sep 14, 2008 at 15:04
Transfer of control in a finally block throws away any exception. The following code does not throw RuntimeException -- it is lost.
public static void doSomething() {
try {
//Normally you would have code that doesn't explicitly appear
//to throw exceptions so it would be harder to see the problem.
throw new RuntimeException();
} finally {
return;
}
}
From http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
-
7It's nasty, but it's also kind of just a logical consequence of how finally works. The try/catch/finally flow control does what it's intended to do, but only within certain limits. Similarly, you have to be careful not to cause an exception inside a catch/finally block, or you'll also throw away the original exception. And if you do a System.exit() inside the try block, the finally block won't be called. If you break the normal flow, you break the normal flow... Apr 20, 2009 at 3:54
-
Don't use finally { return; } but just finally{ code without return}. This is logical, as finally is also intended to be executed when exceptions occurred, and the only possible meaning of a return as exception handler must be to ignore the exception and - indeed - return. May 21, 2009 at 15:21
-
21This seems like more of a "gotcha" than a hidden feature, though there are ways it could be used as one, using this method wouldn't be a good idea.– davenpcjJun 3, 2009 at 20:00
-
Eclipse emits a warning if you do this. I'm with Eclipse. If you want to catch an exception... then catch an exception.– heliosMar 3, 2010 at 15:24
-
That's what you pay for dirty code that returns from middle of method. But still a nice example. Jun 22, 2010 at 12:21
Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.
Instead of:
if( null != aObject && aObject instanceof String )
{
...
}
just use:
if( aObject instanceof String )
{
...
}
-
9It's a shame that this is such a little-known feature. I've seen a lot of code similar to the first block of code. Dec 24, 2009 at 16:20
-
4That's because Java has a special (hidden) null type that you do not see, nor can reference. Jul 1, 2011 at 4:14
-
What's worse is checking for null before
free
ing ordelete
ing in C/C++. Such a fundamental concept. Feb 4, 2012 at 23:04
Allowing methods and constructors in enums surprised me. For example:
enum Cats {
FELIX(2), SHEEBA(3), RUFUS(7);
private int mAge;
Cats(int age) {
mAge = age;
}
public int getAge() {
return mAge;
}
}
You can even have a "constant specific class body" which allows a specific enum value to override methods.
More documentation here.
-
20Really awesome feature actually--makes enums OO and solves a lot of initialization problems in a very clean way.– Bill KOct 6, 2008 at 18:00
-
5
-
6Georgy: Singleton is one instance of the object, not an object with one value.– dshawNov 17, 2008 at 22:43
-
20@Georgy: see also Item 3 in Joshua Bloch's Effective Java (2nd ed); "While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."– JonikApr 21, 2009 at 8:57
-
3Minor nitpick:
mAge
should be final. There's rarely a reason for non-final felds in enums. Oct 6, 2010 at 8:25
The type params for generic methods can be specified explicitly like so:
Collections.<String,Integer>emptyMap()
-
10And by god is it ugly and confusing. And irrelevant to type safety. Sep 16, 2008 at 12:21
-
8I love this. It makes your code a bit more explicit and as such more clear for the poor sod who will have to maintain it in a year or two. May 21, 2009 at 15:30
-
6This is actually very useful in situations where you have declared a static generic method such as
public static <T> T foo(T t)
. You can then make calls toClass.<Type>foo(t);
– FinbarrMay 13, 2010 at 8:20 -
For some reason this doesn't seem to work with statically imported methods.. I wonder why.– oksaytApr 25, 2011 at 17:30
-
This is especially useful when using ternary ifs with a return. For example
return set1.equals(set2) ? new ArrayList<String>(set1) : Collections.<String>emptyList()
. It also useful for some method invocations where a simple Collections.emptyMap() would give a compile error. Jun 30, 2011 at 20:30
You can use enums to implement an interface.
public interface Room {
public Room north();
public Room south();
public Room east();
public Room west();
}
public enum Rooms implements Room {
FIRST {
public Room north() {
return SECOND;
}
},
SECOND {
public Room south() {
return FIRST;
}
}
public Room north() { return null; }
public Room south() { return null; }
public Room east() { return null; }
public Room west() { return null; }
}
EDIT: Years later....
I use this feature here
public enum AffinityStrategies implements AffinityStrategy {
By using an interface, developers can define their own strategies. Using an enum
means I can define a collection (of five) built in ones.
-
12
-
1WHAAAAAT no, I'm with Adrian. This is not Java. This is madness. I'm dying to use this.– salezicaMar 5, 2012 at 9:12
As of Java 1.5, Java now has a much cleaner syntax for writing functions of variable arity. So, instead of just passing an array, now you can do the following
public void foo(String... bars) {
for (String bar: bars)
System.out.println(bar);
}
bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.
-
23The important thing about this is when calling the method, you can write: foo("first","second","third") Mar 25, 2009 at 20:03
-
9so the old hello world can be rewritten; public static void main(String... args) { System.out.println("Hello World!"); } Jan 22, 2010 at 21:56
-
@Karussell Maybe, but it would seem the arguments are irrelevant :p Oct 2, 2011 at 22:41
My favorite: dump all thread stack traces to standard out.
windows: CTRL-Break in your java cmd/console window
unix: kill -3 PID
-
15
-
9
-
2On windows, CTRL-BREAK only works if you have the process running in the current console window. You can use JAVA_HOME/bin/jstack.exe instead. Just provide it with the Windows process id. Aug 24, 2010 at 20:40
-
-
A couple of people have posted about instance initializers, here's a good use for it:
Map map = new HashMap() {{
put("a key", "a value");
put("another key", "another value");
}};
Is a quick way to initialize maps if you're just doing something quick and simple.
Or using it to create a quick swing frame prototype:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
panel.add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
frame.add( panel );
Of course it can be abused:
JFrame frame = new JFrame(){{
add( new JPanel(){{
add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
}});
}};
-
Somehow, it is a bit as if "with" keyword (functionality, actually) have been added to Java. Can be very handy, recently I grunted because init of arrays wasn't available for Collections. Thanks!– PhiLhoDec 13, 2008 at 9:06
-
15There is one side-effect of using this, though. Anonymous objects get created, which may not be fine always.– amitFeb 10, 2009 at 8:14
-
17Although after looking at it more, I have to say I'm strangely attracted to the natural nesting this provides, even the "Abused" version.– Bill KJun 11, 2009 at 21:32
-
4Yep - I quite like the 'abused' version, I think that's really very clear and readable, but perhaps that's just me.– barryredAug 5, 2010 at 15:55
-
3Absolutely agree, the hierarchy of the code reflecting the hierarchy of the gui is a huge improvement over a sequence of method calls.– opsbOct 29, 2010 at 9:08
Dynamic proxies (added in 1.3) allow you to define a new type at runtime that conforms to an interface. It's come in handy a surprising number of times.
-
10Dynamic proxies are a great reason to choose to write a Foo interface and use that everywhere, with a default "FooImpl" class. It may seem ugly at first ("Why not just have a class called Foo?") but the benefits in terms future flexibility and mock-ability for unit tests are handy. While there are ways to also do it for non-interfaces, they typically require extra stuff like cblib.– DarienApr 21, 2010 at 19:57
final initialization can be postponed.
It makes sure that even with a complex flow of logic return values are always set. It's too easy to miss a case and return null by accident. It doesn't make returning null impossible, just obvious that it's on purpose:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 2";
} else {
element = "Result 3";
}
return element;
}
-
That's surprising. Can one fairly say, "The value of a final variable can be set once", no matter where the set occurs? Feb 4, 2009 at 19:12
-
29Yes, but more strongly: "The value of a final variable must be set once" Feb 4, 2009 at 22:15
-
6+1 Agree, this is another valuable tool for spotting errors at compile time, and one that programmers seem shy to use for some reason. Note that because from Java 5 onwards, 'final' also has thread-safety implications, being able to set a final variable during the constructor is invaluable. Apr 20, 2009 at 4:16
-
4Though for this specific method, I'd just use multiple returns. In fact, in most cases where this is applicable, I'd probably refactor it into a separate method and use multiple returns. Nov 17, 2009 at 21:31
-
I love this! I deleted the final keyword always because I thought it will fail. thanks! Jan 25, 2010 at 10:20
I think another "overlooked" feature of java is the JVM itself. It is probably the best VM available. And it supports lots of interesting and useful languages (Jython, JRuby, Scala, Groovy). All those languages can easily and seamlessly cooperate.
If you design a new language (like in the scala-case) you immediately have all the existing libraries available and your language is therefore "useful" from the very beginning.
All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable.
-
18No. It's actually not a very good VM. It was solely designed to run JAVA. Typeless dynamic and functional languages don't work well with it. Of you want to use a VM you should use .NET/Mono. That was designed to work with EVERY language...– Hades32Jun 22, 2009 at 17:33
-
14Actually the JVM is solely designed to run Java Bytecodes. You can compile most modern languages to Java Bytecode. About the only things Java Bytecode is lacking in is dynamic language support, pointers, and tail recursion support. Sep 18, 2009 at 15:43
-
12@Hades32: actually the .NET VM is pretty similar to the JVM. It only got support for dynamic languages relatively recently (with the DLR) and Java 7 is about to get that support as well. And the classical "EVERY language" of .NET (C#, Visual Basic.NET, ...) all have pretty much exactly the same feature set. Nov 27, 2009 at 8:12
-
13JVM doesn't support generics, while the .NET VM does. JVM is nowhere near the best.– BlindyNov 27, 2009 at 8:52
-
3Not to discount the complaints about specific language features not directly supported by the JVM... but I tend to think stability, cross-platform consistency, and good performance are far and above the reasons the JVM gets extra points. I've been working with server-side Java for many years now on many platforms (including AS/400) and have been able to pretty much forget about it entirely -- the bugs are pretty much always in code I can fix, and it simply doesn't crash. Jan 8, 2012 at 20:22
You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.
new Object() {
void foo(String s) {
System.out.println(s);
}
}.foo("Hello");
-
@Vuntic - It does allow you to define a simple class within the context that it is needed. Jul 12, 2010 at 16:49
-
1@Chaos, But why? Got an actual example where it is useful? Dec 3, 2010 at 14:19
-
10@Wouter - In that case, the method which is called on the anonymous object (
start()
) is not actually defined in the subclass...– AxelAug 2, 2011 at 8:35 -
Actually, this is a very useful feature if you extend a base class that does some needed setup, calls the method you write, and then does teardown. Kick the thing off by calling a method in the base class (which I probably wouldn't give the same name). There's an example use (not definition) here Jan 8, 2012 at 6:02
The asList method in java.util.Arrays
allows a nice combination of varargs, generic methods and autoboxing:
List<Integer> ints = Arrays.asList(1,2,3);
-
15you want to wrap the returned list with a List constructor otherwise ints will be fixed size (since it is backed by the array) Aug 4, 2009 at 13:39
-
2The
Arrays.asList
has the unusual feature that you canset()
elements but notadd()
orremove()
. So I usually wrap it in anew ArrayList(...)
or in aCollections.unmodifiableList(...)
, depending on whether I want the list modifiable or not. Dec 3, 2010 at 22:31
Using this keyword for accessing fields/methods of containing class from an inner class. In below, rather contrived example, we want to use sortAscending field of container class from the anonymous inner class. Using ContainerClass.this.sortAscending instead of this.sortAscending does the trick.
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}
-
4That's only necessary if you've shadowed the name (in your case, with the method parameter name). If you'd called the argument something else, then you could directly access the sortAscending member variable of Container class without using 'this'.– sk.Feb 4, 2009 at 17:12
-
7It is still useful to have a reference to the enclosing class, eg. if you need to pass it to some method or construtor.– PhiLhoFeb 14, 2009 at 19:13
-
Often used in Android layout development, in order to get the Context from, say, the listener of a button, with
MyActivity.this
.– espinchiApr 29, 2011 at 17:19
Not really a feature, but an amusing trick I discovered recently in some Web page:
class Example
{
public static void main(String[] args)
{
System.out.println("Hello World!");
http://Phi.Lho.free.fr
System.exit(0);
}
}
is a valid Java program (although it generates a warning). If you don't see why, see Gregory's answer! ;-) Well, syntax highlighting here also gives a hint!
-
15
This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):
public class UnsafeUtil {
public static Unsafe unsafe;
private static long fieldOffset;
private static UnsafeUtil instance = new UnsafeUtil();
private Object obj;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe)f.get(null);
fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
-
20
-
There are a number of other curious methods on Unsafe like creating an object without calling a constructor, malloc/realloc/free style methods. Jul 22, 2010 at 21:11
-
I love esspecially the primitive getters and setters on memory locations, like putDouble(long address, double d).– DanielFeb 26, 2011 at 22:10
When working in Swing I like the hidden Ctrl - Shift - F1 feature.
It dumps the component tree of the current window.
(Assuming you have not bound that keystroke to something else.)
-
1Most likely your window manager has something bound to that key. Gnome doesn't bind to it, so I'm assuming you're running KDE which binds it to 'switch to desktop 13'. You can change it by going to Control panel, Regional, Keyboard Shortcuts and removing the mapping for Shift-Ctrl-F1 Jun 2, 2010 at 14:40
Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.
My vote goes to java.util.concurrent with its concurrent collections and flexible executors allowing among others thread pools, scheduled tasks and coordinated tasks. The DelayQueue is my personal favorite, where elements are made available after a specified delay.
java.util.Timer and TimerTask may safely be put to rest.
Also, not exactly hidden but in a different package from the other classes related to date and time. java.util.concurrent.TimeUnit is useful when converting between nanoseconds, microseconds, milliseconds and seconds.
It reads a lot better than the usual someValue * 1000 or someValue / 1000.
Language-level assert keyword.
-
19The trouble with assert is that it needs to be switched on during runtime. May 21, 2009 at 15:42
-
10But if it's disabled it's like it's not there. You can add as many asserts as you want in your code and you won't have any performance penalty if they're disabled. Aug 9, 2009 at 5:15
-
5I believe that’s a good thing about assert: it can be turned off without penalty.– andrefJul 11, 2010 at 17:41
-
the problem is, if you accidentally implemented a side effect in an assert, you've got to turn on assertion for ur program to work...– ChiiOct 12, 2010 at 11:15
-
To detect if asserts are on, you can use { boolean assertsOn = false; assert assertsOn = true; if (assertsOn) { /* complex verification */ } }. This also allows to log or throw exception if state of assert is not the expected. Jun 23, 2011 at 18:26
Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.
The addition of the for-each loop construct in 1.5. I <3 it.
// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
System.out.println(foo.toString());
}
And can be used in nested instances:
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
-
30I think using
i
here is super-confusing, as most people expect i to be an index and not the array element.– cdmckayFeb 23, 2009 at 7:28 -
So... int sum(int[] array) { int result = 0; for(int element : array) { result += element; } return result; }– DrewMar 10, 2009 at 23:27
-
28The only thing that drives me nuts about this is that it seems like it would be really really easy to create a keyword for accessing the loop count value, but you can't. If I want to loop over two arrays and make changes to a second based on values in the first I'm forced to use the old syntax because I have no offset into the second array.– JhericoMay 19, 2009 at 21:34
-
6It's a shame it doesn't also work with Enumerations, like those used in JNDI. It's back to iterators there. May 21, 2009 at 15:32
-
3@extraneon: take a look at Collections.list(Enumeration<T> e). That should help with iterating enumerations in the foreach loop. Mar 24, 2010 at 23:49
i personally discovered java.lang.Void
very late -- improves code readability in conjunction with generics, e.g. Callable<Void>
-
2not quite. at some point, you need to be specific: Executors.newSingleThreadExecutor().submit(new Callable<Void>() {..}) -- you can't instantiate a new Callable<?>(), you need to specify an explicit type -- thus, it's an alternative to Callable<Object>. Jun 17, 2009 at 14:59
-
4Void is more specific than Object as Void can only be null, Object can be anything. Jul 22, 2010 at 21:14