Java for( x : y) execution - java

I have the following for loop:
for(String s : someString.split("\\s+")){
//do something
}
Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?

It only does it once, and uses that array and interates through it.
Edit: from Mat This is the reference

It stores the array in a temporary variable before using it.

No the split is executed once on the string and after that the loop iterate over the result

The split method is only called once. Think of the structure (also known as a for-each) as follows:
The second argument is evaluated and kept for the duration of the loop.
If the argument gives an Iterable or is an array (special case), a check is then made to see if the type of the first argument corresponds with the elements that are returned.
The process enters the loop and executes the code inside the scope and exits when there are no more elements left.
More information can be had here:
http://www.leepoint.net/notes-java/flow/loops/foreach.html
P.S: This works with Java 5 minimum.

Related

what does this line make in the arrays?

Im checkin a code in c++ and i'm trying to "translate" it to java. i wonder what this line does... (both are int arrays)
frequencies[values[i]]++;
and how can i translate it?
This is the code I extrated the line from
https://github.com/Tomaszal/HackerEarth/blob/master/Data%20Structures/Stacks/Fight%20for%20Laddus/main.c
I believe it gets the value from the i-th element in the values array, searches for it in the frequencies array and add 1+ to the index...I don't really get it
This was my attempt to the code above
int y=values[p];
frequencies[y]=frequencies[y]+1;
It gets the value from i-th element in the values array and passes this value as an indexer to frequencies array and increments the returned value by 1. A perfect translation would be
Increment the (i-th value)th value of frequencies by 1.
and it surely works the same in Java. You don't need to convert it to any other statement(s) in Java to work.

Accessing specific element from two dimensional character array

I'm working on a method that takes as input a two dimensional array, a character and 2 integers giving the location of the character in the array. I have to throw an exception whenever the array is full at the location i'm trying to access, or whenever i'm trying to access a location that is out of bounds. Java is giving me a weird error in relation to how I have written my code. I am not sure how to access a certain element from a two dimensional array. I have attached a screenshot of my code and the exception I get.
Thank you in advance! Here is the image
It may be preferable to copy and paste the code and the Exception straight to the question body with monospace formatting for easier readability.
The charAt function is expected to be called on a String object. A char[][] array is not a String object, so the code won't compile successfully. Depending on your familiarity with Java you may want to read up on the difference between a class object (such as an instance of the String class) and an array of primitive types (such as char).
Tutorial page explaining arrays: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Tutorial page explaining classes:
https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
If you're trying to access a char from a two-dimensional char[][] array, just think of it like accessing an array of arrays. char[x] will get you the "row" containing the element you want and char[x][y] will get you the specific element in that "row" of elements.
Since your array is a char array you do not need to put board.charAt[x][y] just board[x][y]. Also the finally bit is always executed so if you put illegal values for x or y you will still get an error. Furthermore you are not writing the character referenced by the variable c to the array, you are writing the character (letter) c into the board.
You can use the second if statement with an else to put the character in the array and avoid the finally altogether.
if(board[x][y] != ' ') throw new IllegalArgumentException("Your message");
else board[x][y] = c;
which should go inside the first if that you've gotten.
Another approach is to use catch after the try because trying to access an element outside of the array will throw an Exception anyway.

ArrayList/LinkedList get First Index number

Is is possible to get out of an ArrayList the first number of the first index?
Here's an Example:
In there are 5 items:
path = {0.5,5.0},{0.6,6.0},{0.7,7.0},{0.8,8.0},{0.9,9.0}
And I want to get the number 5.0 out of {0.5,5.0}...
I tried it with path.get(0) But it only gives me {0.5,5.0} back.
Is it possible to get 5.0 out of it without getting all the other numbers?
If your ArrayList contains arrays, this is the way to go
myList.get(0)[1] // You're getting the index 1 from the 1st array of your ArrayList
Otherwise, if it is containing other ArrayList's
myList.get(0).get(1) // Same logic as above applied to the Collection
If your curly braces in the ArrayList are actually brackets (they probably are), you can use:
myArray.get(0)[index] to get the index you want. In your example it is:
myArray.get(0)[1];
Note: if your ArrayList elements are also ArrayList then you need to use get(0).get(1) instead of get(0)[1].

Why did the first for loop fail in Java? [duplicate]

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()

Finding path between two nodes without mentioning the number of loop to iterate

Situation here, I just do not want to loop externally in java for a gremlin query. Like I want to fetch all the paths or rather the name of the nodes/ edges in between of two separate nodes.
Here the first query with loop would be
(Name of the first Node).loop(1){it.loops<100}{true}.has('name', (Name of the second node)).path{it.name}
converting which in java has taken a lots of code !
but in case of the above there is a loop which looping for 100 nodes. If I try to traverse through any big number of nodes. or the count is not numerable to me then how the full traversal would be ?
here I have got one suggestion like : g.v(100).out.loop(1) { it.object != g.v(200) }.path
How will it directly work inside java ? I want to avoid groovy !
If you don't know the number of steps to loop you can just do:
g.v(100).out.loop(1){true}.path
That first closure after the loop represents a function that accepts loop metadata and return a boolean that decides whether or not to continue the looping process (true) or to terminate (false). As I simply return true above, the loop will not cease until all the paths are exhausted. Of course, the problem there is that if the graph cycles, the traversal will iterate indefinitely. It is therefore only safe to do a {true} if you are certain that your graph structure is such that you won't fall into that trap.
It is far better to simply have a max loop length of some reasonable size so that the traversal terminates. Or, alternatively, you could have some other intelligent method for managing loop termination. Maybe you could terminate the loop after some number of cycles is detected.
As far as wanting a Java answer instead of a groovy answer, I suggest that you read this answer about this topic. It explains how you go about converting groovy to java. For your specific problem, here's the java:
new GremlinPipeline(g.getVertex(100)).out().loop(1,
new PipeFunction<LoopPipe.LoopBundle<Vertex>,Boolean>() {
public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) {
return true;
}
}, closure)

Categories

Resources