Explain this Java for expression - java

Can anyone explain this code to me?
class className {
int[] coeffs;
int count(int value) {
int count = 0;
for (int coeff: coeffs)
if (coeff == value)
count++;
return count;
}
}
What I really don't understand is this part:
for (int coeff: coeffs)
What is it mean? Thanks for help.

In earlier versions of Java, there was only the C/Fortran style "for()" loop.
Java 5 (JDK 1.5, 2004) introduced a "foreach()" loop, with the syntax you've described:
http://en.wikipedia.org/wiki/Foreach_loop#Java
for (type item: iterableCollection) {
// do something to item
}
It's worth noting that although the newer "foreach" syntax might be more "elegant", the "old" for loop index can actually be faster:
https://www.java.net//node/662136

That is the enhanced for each loop to loop through the array int[] array.
Look at the Oracle documentation

This is a foreach loop - it means that for every value in the array coeffs the code inside the for loop will be executed, with the variable coeff representing the value used during that particular iteration.

That's an enhanced for loop. It is structured as follows:
for(Object o: collection)
Basically, objects is an array of objects or primitive, or an Iterable of objects.
Java will iterate over the array or Iterable, set o to the object/value retrieved, and process the block. It allows for quick iteration without dealing with handling your own iterators/

Related

Need help using java.lang.reflect.Array to sort arrays

An interview question was to write this method to remove duplicate element in an array.
public static Array removeDuplicates(Array a) {
...
return type is java.lang.reflect.Array and parameter is also java.lang.reflect.Array type.
How would this method be called for any array?
Also not sure about my implementation:
public static Array removeDuplicates(Array a)
{
int end=Array.getLength(a)-1;
for(int i=0;i<=end-1;i++)
{
for(int j=i+1;j<=end;j++)
{
if(Array.get(a, i)==Array.get(a, j))
{
Array.set(a, j, Array.get(a, end));
end--;
j--;
}
}
}
Array b=(Array) Array.newInstance(a.getClass(), end+1);
for(int i=0;i<=end;i++)
Array.set(a, i, Array.get(a, i));
return b;
}
You may want to consider using a different data structure such as a hashmap to detect the duplicate (O(1)) instead of looping with nested for loops (O(n^2)). It should give you much better time complexity.
There are various problem with this code. Starting here:
if(Array.get(a, i)==Array.get(a, j))
Keep in mind that those get() calls return Object. So, when you pass in an array of strings, comparing with == simply will most likely result in wrong results (because many objects that are in fact equal still have different references --- so your check returns false all the time!)
So, the first thing to change: use equals() instead of == !
The other problem is:
end--;
Seriously: you never ever change the variable that controls your for loop.
Instead: have another counter, like
int numberOfOutgoingItems = end;
and then decrease that counter!
For your final question - check the javadoc; for example for get(). That reads get(Object array, int index)
So you should be able to do something like:
int a[] = ...;
Object oneValue = Array.get(a, 0);
for example.
Disclaimer. I have to admit: I don't know if the Array implementation is smart enough to automatically turn the elements of an int[] into an Integer object.
It could well be that you have to write code first to detect the exact type of array (if it is an array of int for example); to instead call getInt() instead of getObject().
Beyond that, some further reading how to use reflection/Array can be found here

Loop variable in enhanced for loop

The following works fine,
int i;
for (i = 0; i < 10; i++) {}
But this doesn't
// a is an ArrayList of Integers
Integer i;
for (i: a) {}
and I'm forced to do it this way:
for (Integer i : a) {}
Why is it that the second loop doesn't work?
Think about it this way: What would happen if you always initialized your variable?
In the first case: It's initialized IN this example, clearly no problem.
In the second case: You initialize it, to say, 1. Now you have a variable, "1", and you throw it into this for loop. "for( 1 : a)". What does that mean?? And if you override the value of "i" for every value in a, then when it comes out of the loop it's simply the last entry in A. Again, what does that really mean? Why would that be useful? How does the effect the rest of the code outside of this loop? It's bad design to support that, it would result in all sorts of crazy, unexpected behavior and unreadable code.
In the third case: Your variable is explicitly declared IN the scope of that loop, and is very clearly temporary. It will do its job of extracting what you need from this array and be done with. Any modifications to outside pieces of code will need to happen intentionally with explicit setters. Note that you can't initialize it here, because initializing is meaningless.
For the for loops, you need 3 statements.
Your second loop only has 2 statements, and your first one has 3. On top of that, you never initialized your integer i. Make sure to do
int i =0;
for(i;i<=10;i++){
}
For enchanced for loops, you must have
for (String element : array) {
System.out.println("Element: " + element);
}
You can check out this link, it might help. What is the syntax of enhanced for loop in Java?
You have to explicitly give the type of object that you are iterating over in the array list. In the first for loop you are just plugging in the index. In the second, you are trying to have the for loop grab the object without knowing what kind of object it is.
The enhanced for statement is equivalent to a basic for statement of the form:
for (Iterator i = Expression.iterator(); i.hasNext(); ) {
TargetType Identifier = (TargetType) i.next();
...
}
14.14.2. The enhanced for statement
This one is normal for loop using. You can declare the variable type outside the for
int i;
for (i = 0; i < 10; i++) {}
or
Integer i;
for (i = 0; i < 10; i++) {
System.out.println(i);
}
the second one, if you would like to use foreach(also known as Enhanced For-loop) with the Generic type, the syntax must be:
for(data_type variable : array | collection){}
Hope this help!
As per JLS (see very bottom of 15.27.2. Lambda Body) - in each iteration of enhanced-for loop we have a brand-new i variable => we cannot reuse (Integer i;) variable declared before the loop.
We have a brand-new variable in each loop, hence we have declaration syntax here: for(Integer i : array) as it is really declared again and again on each iteration.
Proof comes from JLS code example about lambdas:
void m9(String[] arr) {
for (String s : arr) {
foo(() -> s);
// Legal: s is effectively final
// (it is a new variable on each iteration)
}
}

Foreach vs common for loop

I just started learning Java and the first thing I came across is the foreach loop, not knowing the way it works the first thing I did was:
int[] array = new int [10];
for (int i: array){
i = 1;
}
And obviously failed to assign 1 to every element of the array. Then I added System.out.print(i); (after i = 1;) to the body of the loop and saw that the output of the screen was 1111111111 but since doing something with i inside the loop is valid that most likely i is a copy of every element of the array, ain't it? (first questions)
If the above is true doesn't this mean that the foreach loop is much slower then the common for loop since it involves making copies of each element of the array? Or since Java doesn't have pointers and pointer arithmetic, the oprator[] may be designed in some other "badly" fashion that copying every element is actually faster?
And if the above assumptions are true, why one would use an obviously slower foreach loop instead of a common forloop?
In short the questions:
Is i the copy of each element of the array? If not what is it
then?
Isn't the foreach loop slower then the common one? If not, how
"badly" is then operator[] designed?
There is nothing more except readability to win in a foreach loop?
In the code
for (int i: array){
You declare a variable i that on each loop iteration gets the value of the next element in the array, it isn't a reference to that element.
In
i = 1;
you assign a new value to the variable, not to the element in the array.
You cannot set the values of array elements with a foreach loop directly. Use a normal for loop for that
for (int i = 0; i < array.length; i++) {
array[i] = ...; // some value
}
In the above example, you are using the declared variable i as an index to the element in the array.
array[i]
is accessing the element itself whose value you can modify.
Ans obviously failed to assign 1 to every element of the array. The I
added System.out.print(i); to the body of the loop and saw that the
output of the screen was 1111111111 but since doing something with i
inside the loop is valid that most likely i is a copy of every element
of the array, ain't it? (first questions)
You must have put the System.out.print(i) after the i = 1, otherwise you would get 0000000.
If the above is true doesn't this mean that the foreach loop is much
slower then the common for loop since it involves making copies of
each element of the array? Or since Java doesn't have pointers and
pointer arithmetic, the oprator[] may be designed in some other
"badly" fashion that copying every element is actually faster?
Have a look here to see how the foreach loop works. For arrays,
for (int i: array){
i = 1;
}
is equivalent to
for (int index = 0; index < array.length; index++) {
int i = array[index];
i = 1;
}
So it isn't slower. You're doing one more primitive creation on the stack.
It depends on the implementation. For arrays, it's not slower in any way. It just serves different purposes.
why one would use an obviously slower foreach loop instead of a common
forloop?
One reason is for readability. Another is when you don't care about changing the element references of the array, but using the current references.
Take a reference type example
public class Foo {
public int a;
}
Foo[] array = new Foo[3];
for (int i = 0; i < array.length; i++) {
array[i] = new Foo();
array[i].a = i * 17;
}
for (Foo foo : array) {
foo.a = 0; // sets the value of `a` in each Foo object
foo = new Foo(); // create new Foo object, but doesn't replace the one in the array
}
With primitive types such a thing doesn't work.
for (int index = 0; index < array.length; index++) {
int i = array[index];
i = 1; // doesn't change array[index]
}
From Item 46 in Effective Java by Joshua Bloch :
The for-each loop, introduced in release 1.5, gets rid of the clutter
and the opportunity for error by hiding the iterator or index variable
completely. The resulting idiom applies equally to collections and
arrays:
// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
doSomething(e);
}
When you see the colon (:), read it as “in.” Thus, the loop above
reads as “for each element e in elements.” Note that there is no
performance penalty for using the for-each loop, even for arrays. In
fact, it may offer a slight performance advantage over an ordinary for
loop in some circumstances, as it computes the limit of the array
index only once. While you can do this by hand (Item 45), programmers
don’t always do so.
Advantages
Readability
It increases the abstraction level - instead of having to express the low-level details of how to loop around a list
or array (with an index or iterator), the developer simply states that
they want to loop and the language takes care of the rest.
Disadvantage:
Cannot access the index or to remove an item.
To sum up,
the enhanced for loop offers
A concise higher level syntax to loop over a list or array which
1.1 improves clarity
1.2 readability.
However, it misses : allowing to access the index loop or to remove an item.
Setting the values by reference didn't work because int is a primitive type. For any kind of Object[] it would work. Making a copy of a primitive type is very fast, and will be done by the processor many times without your realising.
The foreach loop is more readable, but it's also more writeable. A common programmer error is:
for (int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; i++) //oops, incrementing wrong variable!
{
//this will not execute as expected
}
}
It's impossible to make this error using a foreach loop.
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
So, you're right. Readability is the main win here. For further information on the for each loop, or enhanced for loop, here a blog entry from oralce.
The for each utilized the functionality of the Iterable<E> interface, so the performance depends on the implementation.

Java: Counting instances in an object

I have the code:
int number;
for (Vartype var : dataset) {
number++;
}
This code does work, but var is never used. How else can this code be written so Java isn't complaining about an unused variable? "dataset" is an object.
Java's not complaining about the unused variable, your IDE is.
Instead of looping over each object in that array/Collection, you can just use its size to see how many elements are there.
// if dataset is an array:
int number = dataset.length;
// if dataset is a Collection:
int number = dataset.size();
The for-each as per your post will count the number of members in 'dataset' if it is a collection object.
You can also use for-loop for this.
or simply check the size of the object if it is a collection object.

Does Java's for-each call an embedded method (that returns the collection) for every iteration?

If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the "enhanced for" loop):
for (ArrayElement e : MyClass.returnArray()) {
//do something
}
will then the returnArray() method be called for every iteration?
No, it won't. The result of the first call will be stored in the compiled code in a temporary variable.
From Effective Java 2nd. Ed., Item 46:
Note that there is no performance penalty for using
the for-each loop, even for arrays. In fact, it may offer a slight performance advantage
over an ordinary for loop in some circumstances, as it computes the limit of
the array index only once.
From the java language spec:
EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement
and later on:
T[] a = Expression;
L1: L2: ... Lm:
for (int i = 0; i < a.length; i++) {
VariableModifiersopt Type Identifier = a[i];
Statement
}
This is (in pseudo code) the equivalent of the advanced for loop for arrays. And it is made clear, that the Expression is evaluated once and the resulting array is assigned to T[] a.
So it's perfectly safe to use even complex expressions in the advanced for loop statement.
No.
The for loop is just syntactic sugar. It behaves differently depending on whether or not it is applied to an Array argument or an object implementing the Iterable interface.
For Iterable objects, the loop expands to something like this:
Iterator<ArrayElement> iter = iterableObject.iterator();
while (iter.hasNext()) {
ArrayElement e = iter.next();
// do smth
}
What your example code is actually doing is something like this:
Object[] temp = Method.returnArray();
for ( int i = 0; i < temp.length; i++ ) {
ArrayElement e = (ArrayElement) temp[i];
// do smth
}
No, it will be called once. It's not like the termination condition of a standard for loop, which gets evaluated on every iteration.

Categories