This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 3 years ago.
I have tried binary recursion to find the nth Fibonacci number (or the whole Fibonacci series by using a for loop in main()) but according to Data Structures and Algorithms in Java (6th Edition) by Michael T. Goodrich; it is a terribly inefficient method as it requires an exponential number of calls to the method. An efficient recursion technique is linear recursion given as follows;
/**Returns array containing the pair of Fibonacci numbers, F(n) and F(n-1)*/
public static long[] fibonacciGood(int n) {
if(n<=1) {
long[] answer = {n,0};
return answer;
}else {
long[] temp = fibonacciGood(n-1); //returns {F(n-1), F(n-2)
long[] answer = {temp[0]+temp[1], temp[0]}; //we want {F(n), F(n-1)}
return answer;
}
}
Whenever I run the code it returns a reference as
[J#15db9742
which is not the desired answer. What should I write in main() so that i can have the desired answer?
Try the one below. You can refer the api here.
public static void main(String[] args) {
System.out.println(Arrays.toString(fibonacciGood(4)));
}
You are trying to print out an array to the console, this is causing the memory address of the array to be output. You may want to iterate through the array returned, printing every element to get the desired output.
Here you are printing the array object, so you are getting these results. Internally it calls toString method of the object, which return getClass().getName() + "#" + Integer.toHexString(hashCode());. So you are getting value as [J#15db9742.
You can use convert is directly as below (Working in Java version 5 and above)
System.out.println(Arrays.toString(fibonacciGood(4)));
You can print it by converting it to list as below (in Java 8 or above) (Not Preferable to use streams here, but just for knowledge):
System.out.println(Arrays.stream(fibonacciGood(4)).boxed().collect(Collectors.toList()));
Related
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}
This question already has answers here:
Variable used in lambda expression should be final or effectively final
(9 answers)
How to sum a list of integers with java streams?
(12 answers)
Closed 4 years ago.
The following snippet does not compile. How to find the sum using forEach as shown below?
private int Sum(ArrayList<Integer> inputs) {
int sum = 0;
inputs.stream().forEach(x -> sum += x);
return sum;
}
This should do the trick:
private int Sum(ArrayList<Integer> inputs) {
return inputs.stream().mapToInt(Integer::intValue).sum();
}
EDIT :
The problem with using for-each is that it is a terminal operation, which means that it doesn't produce another intermediate stream for us to work on. The better approach would be to use mapToInt which produces an IntStream on which we can easily find the sum.
This answer is just to provide a bit more context as to why your code doesn't work and therefore allowing you to decipher the problem if it were to happen in the future.
It seems like you're a .NET user which makes it completely understandable for one to expect the code you've written to work. As in .NET the equivalent would be:
private int Sum(List<int> inputs) {
int sum = 0;
inputs.ForEach(x => sum += x);
return sum;
}
However, in java variables used in a lambda expression must be final or effectively final, for that reason the statement inputs.stream().forEach(x -> sum += x); will not compile.
Nevertheless, simply because one would expect the aforementioned code to work in C# doesn't necessarily mean it should work in Java as there are different rules.
There are solutions available to find the sum of a set of numbers using the forEach method but it's not the idiomatic approach and so should be avoided unless necessary.
The idiomatic approach is as #Nicholas K has shown.
On another note:
even in .NET the idiomatic approach would be return inputs.Sum();
as opposed to using the ForEach extension method to sum the elements of a given list.
whenever you seem to see yourself use inputs.stream().forEach(...); in java you should instead do inputs.forEach(...) as all lists have a forEach method.
method names in Java should be camelCase as opposed to PascalCasing as in C#.
This question already has answers here:
Finding the median value from a List of objects using Java 8
(6 answers)
Closed 4 years ago.
How to find median value by using java stream API :
For example I have the following array int []arr ={0,1,2,4,6,5,3};
Is there a way and what is the best way to find the median value using java Stream API;
int findMedian() {
int []arr ={0,1,2,4,6,5,3};
IntStream.of(arr).sorted() // what I have to do here
return 0;
}
And what do you think if I changed to a parallel stream for the big array, will it be faster or not ? Is sorting will be on parallel?
I suggest you pass the array to findMedian (and since it doesn't access any fields, make it static). Then you could sort it, convert that back to an array and return the element at half the length. Like,
static int findMedian(int[] arr) {
return IntStream.of(arr).sorted().toArray()[arr.length / 2]);
}
or, skip that many elements and limit it to the first result. Like,
return IntStream.of(arr).sorted().skip(arr.length / 2).limit(1);
This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Java native array lengths
(6 answers)
Closed 9 years ago.
Let's say I create an array of ints with length 10, i.e.
int[] array = new int[10];
At some point in my code, I want to compare the value of an int variable, let's call it var, with the length of the array.
I would like to know if this piece of code:
if(var == array.length) { // stuff }
and this piece of code:
if(var == 10) { // stuff }
which do exactly the same thing, have also the same performance.
In other words, I would like to know the internal mechanics that the JVM (?) uses to find the length of the array (I don't say "to return" since length is a field, not a method). Does it make use of iteration? Because if it does, then the 2nd piece of code would be faster than the 1st one.
EDIT: Similar question regarding array.length cost (even though focusing more to its use in for loops):
What is the Cost of Calling array.length
.length is a property, so it would not do iteration for sure. Still, the value of the property is, naturally, fetched at runtime, meaning that the second solution will be a little bit faster (as this is comparison with constant).
Still the first implementation is far more preferable:
This makes your code quite more maintainable
You can alter the length of the array only at one place
You will never feel the performance difference unless you pass through this if litterally millions of times in a second.
EDIT By the way you can yourself tell this is a property - there are no braces after the call. I at least do not know of a way in java to make property access do additional computation, but just retrieving its value.
.length is a property of the array, not a function. Thus, the result would be available immediately, with no iteration necessary.
From the Java Doc
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
length is an final field of array, so no iterations are required while writing following code.
if(var == array.length) { // stuff }
And it is good coding practice indeed.
The length property of an array is extracted in constant (O(1)) time - there is no iteration needed. It's also good practice to use this.
This question already has answers here:
Where is Java's Array indexOf?
(13 answers)
Closed 9 years ago.
I need to assess the last int in an array where a certain conditional is met. My program can work out what that int is, but it needs to also know where it's position was in the array. I searched on stack-exchange and someone posted this:
Arrays.asList(array).indexOf(indexPos);
As a possible solution, but I am not sure if I am doing it right, because I get the error
cannot find symbol. I also allowed:
int test = Arrays.asList(array).indexOf(indexPos);
And then tried to print test, but I could not even get to that point. Thanks.
You may need to import java.util.Arrays to get the symbol.
There is no guaranteed way of finding the position of an element in an array except for looping over the array - that is basically what your asList snippets are doing.
This will work as long as your arrays don't have duplicate values. If you need to handle duplicate values, you may need to rethink you data structs.
Someone posted a similar question that someone else asked. It seems that this has worked for me.
The Code is:
java.util.Arrays.asList(seq).indexOf(indexPos);
and the Question:Where is Java's Array indexOf?
Yes you have the method defined in List interface. So you need to use asList() function followed by indexOf() function.
If the array is not sorted you can use java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search function(improves performance) java.util.Arrays.binarySearch(theArray, o)
As for the error make sure you have imported java.util.Arrays. Also that you have defined Array seq and int indexPos which makes your code int test = Arrays.asList(seq).indexOf(indexPos);.