Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ":" doing in this beginners java example program using generics?

Okay so I need help understanding something. I understand how "? :" are used together but reading over some beginning Java stuff I see this situation popping up in a few places. Most recently is this...

public static <U> void fillBoxes(U u, List<Box<U>> boxes) {
    for (Box<U> box : boxes) {
        box.add(u);
    }
}

What I am confused about is what exactly ":" is doing. Any help would be appreciated. I am looking at this example on a page at Oracle's website, located here: http://download.oracle.com/javase/tutorial/java/generics/genmethods.html

like image 864
CrazyGrunt Avatar asked Jan 19 '23 17:01

CrazyGrunt


2 Answers

That is Java's for-each looping construct. It has nothing to do with generics per-se or: is not for use exclusively with generics. It's shorthand that says: for every type box in the collection named boxes do the following...

Here's the link to the official documentation.

Simpler code sample: (instead of managing generics performing a summation of an int array)

int[] intArray = {1,5,9,3,5};
int sum = 0;
for (int i : intArray) sum += i;
System.out.println(sum);

Output: 23

like image 106
Paul Sasik Avatar answered Feb 02 '23 00:02

Paul Sasik


That's the "foreach" form of the for loop. It is syntactic sugar for getting an iterator on the collection and iterating over the entire collection.

It's a shortcut to writing something like:

for (Iterator<Box<U>> it = boxes.iterator(); it.hasNext(); ) {
    Box<U> box = it.next();
    box.add(u);
}

For more see this Oracle page which specifically talks about the "foreach" loop.

like image 35
QuantumMechanic Avatar answered Feb 01 '23 22:02

QuantumMechanic