This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 5 years ago.
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like
for(String x : model)
Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?
It means the loop will iterate through each object of the list
String x declares a String named x
model is the list of String you want to iterate through
: is the operator making the compiler doing this operation.
You can read the for like this : For each String in model, use x as variable and do the following operations.
you can then use x to do the operations you want on each elements of the list
In this context, : literally means in.
This is the syntax of the enhanced for loop. It marely means that you're iterating over all the elements in model, where in each iteration the String x is assigned with the current element so you can use in the loop's body.
Similar to mathematical notation that represents elements in a set.
Read left to right; For all string's x that are elements in model, do .
Related
This question already has answers here:
Is ++x more efficient than x++ in Java?
(3 answers)
Closed 6 years ago.
I'm reading C++ 101 Rules Guidelines and Best Practices, and at item 28, they state that post increment operator should be avoided if we don't need the old value of the variable, as this operator creates a copy of it, hence a tiny performance loss.
I was wondering if Java did this operation the same way, in which case prefix operator should also be prefered for for-loop statements (the ones that might not be suited to a for-each or a lambda forEach() statement)
Java specs tell (ยง15.14.2):
The value of the postfix increment expression is the value of the variable
before
the new value is stored
So, is there some new object created at any time during the operation ? As we're returning something different than the variable that's been incremented.
Yes, there is. This method might explain it:
int iplusplus(int i){ //this is just an example. in real java, this would be a copy of i
int old = i; //this is the copy that might be unneeded
i = i+1; //this is the actual increment
return old;
}
old is the copied value. If you just want to increment i, ++i is shorter:
int plusplusi(int i){
return i+1;
}
As mentioned, this method is not the same, as the parameter i would be a copy and you would not change the variable's value in the calling code.
This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()
This question already has answers here:
Java, How do I get current index/key in "for each" loop [duplicate]
(6 answers)
Closed 8 years ago.
Overview:
I'm using for-each loops and I'm curious if I need to replace them with regular for loops, or if there is a way to do a locate in an ArrayList which will give me the equivalent of keeping track of the index which is used in normal for loops.
Simplified Version of the Problem:
I'm using for-each with an ArrayList of objects. These objects are used to calculate different values at different times, so I need to iterate through the items and do the calculates a couple different times. I wish to track these results in a structure, which I can easily do, if I can locate items in an ArrayList (without having to iterate through everything in a separate loop). If there is, then I can use that to build what I need. If not, I'll replace the for-each with for loops and get the functionality I need.
You can use a regular for-loop but sometimes it just isn't a good idea, for example if you're dealing with linked lists where element retrieval is O(n) in the index. Why not just keep track of index?
int index = 0;
for (Element e : list) {
...
index++;
}
I find this cleaner than a plain for-loop, and it will remain efficient even if you change from ArrayList to another type of list which is not random-access.
The for-each loop is meant to be an easy way to operate on every element in a collection or array. If you want to iterate and keep track of indicies, you'll want a normal for loop.
However, some Collections (Lists for example) have an indexOf() method which you can use to get the index. That would kill your performance though.
You can also use a counter:
int i = 0;
for (Object o : list) {
// Code
i++;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android (method for checking an arrays for repeated numbers?)
I've just asked a question and got a few answers and i was very happy to, but there were very complicated answers, I'm quite new to android so can some one maybe give me some example code or some think explained not the complicated. I've tried there code and tried to make sense of it but i cant.
here is the question....
could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to call a method or something like that. Is there a method to check this or something similar? or would i have to do it using loops and if statements, which i have tried but is getting a bit long and confusing. Any advice would be great, thanks.
int test[] = {0,0,0,0,0,0,0}; (The Array)
(A method to check if any of the arrays numbers are repeated)
First don't make double topic.
Second you are searching for a Java answer not related to Android.
I think that maybe it's better if you first learn java (or other language like).
I would store the items in a Set if you do not want them to repeat. If add returns false then you have a repeating number
Set uniqueItems = new HashSet();
for(int i=0;i<test.length;i++)
if(!uniqueItems.add(test[a]))
System.out.println("The item is already in the set");
First, sort the array. Then search through the array comparing each node to the node on either of it's sides. Or you could store the data in a Set which cannot have duplicates.
Arrays.asList(test).contains(valueYouWantCheck).
If you want to find out for each and every value in test array, Yes I think you need to loop the array.
I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.
for (i=0; i < Question.length; i++)
{
object.dostuff
}
Many things have to happen first:
Initialize the array: seems you got that one covered.
Initialize objects within the array: Make sure every cell of your array actually contains a question instance (or to be more precise: a reference to a Question instance).
Iterate over the array: here your loop seems to go over the class (Question, with capital Q) but you need to iterate over the array (question with a small q). Piece of advice, since the variable question here represents an array of question it would make more sense if you make your name plural (questions) to help illustrate that this is an array. Basic rule is to make the name as explicit as possible, so questionArray would be an even better name. Past a certain point it's a question of taste. Rule of thumb is that if you have to look at the declaration of the variable then it's probably not named correctly.
access methods, properties etc of the objects: when iterating over the array you need to access the right index (questions[i]) then access the members of this object (questions[i].doStuff). If you aim for OOP (which I assume is the point here) then you may want to make the obvious operations as functions of your Question class. Then simply call this function with the proper parameter (questions[i].setNumber(i)). It all depends on what you need it to do.
Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).
Don't use Question.length, use question.length
Add an accessor method and a method to increment the scores.
use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.
list=[("1 this is sentence 1","1 this is sentence 2",1),("2 this is sentence 1","2
this is sentence 2",2),("3 this is sentence 1","3 this is sentence 2",3)]
numbers=map(lambda x: x[2],list)
result=reduce(lambda x,y: x+y,numbers)
print(result)
output:
6