what do the square brackets mean? in Java - java

What does it mean when there are square brackets in front of double. For example double[]?
Is there any special way to use the return function when using them in a method.
For example:
public double[] MethodName(){
}
What is the type of the return value?

Square brackets [] would indicate an array. In your case of code:
public double[] MethodName(){
....
}
You have a public method MethodName which returns an array. Double indicates what type the array is, i.e. stores an array of objects of type double.
EDIT: Forgot about answering your return question. But for your line of code, MethodName would return an array of type double (which would depend on the implmentation inside the method body). Hope that helps (I'm new to Java too; climbing the SO rep ladder)

Related

Error in Math.random() for arrayList

I'm sure this is a small, stupid error that I just can't see.
I'm getting a compiling error in this code:
private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
in my length.
Compiling error is:
"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList "
How can I fix this? I do want to use Math.random();
Also not sure if this makes a difference, but this is is being done within a String method.
Thanks in advance!
if cities is of type ArrayList you have to use cities.size() instead of cities.length.
There are a couple of errors here.
First: If your method is not void is because you're gonna return something, in your method you should return a String.
Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double
Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.
So, the easier fix would be just changing the string and int for double and return it like this:
private static double setQuestions(){
double match = Math.floor(Math.random()*cities.length);
return match;
}
Remember if you want to use the double returned you should store it when you call it, like this:
double result = setQuestions();
Hope it helps!
The code has three problems:
First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.
Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();
Third, your method requires an String as return, than you should return the String object correctly.

What does int[]... arrays mean in Java?

Can you help me? What does int[]... arrays mean in Java?
Example:
public static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
That is called varargs.. notation,
So that you can pass individual int[] objects to that method,, without worrying of no.of arguments.
When you write
public static int[] concat(int[]... arrays) {
Now you can use that method like
Classname.concat(array1,array2,array3) //example1
Classname.concat(array1,array2) //example2
Classname.concat(array1,array2,array3,array4) //example3
A clear benefit is you need not to prepare an array to pass a method. You can pass values of that array directly.
It means that the concat function can receive zero or more arrays of integers (int[]). That's why you can loop over the arrays argument, accessing one of the arrays contained in each iteration - if any. This is called variable arguments (or varargs).
Check this other question for more info.
This means, that you can pass zero, one or more arrays of int (int[]) to your method. Consider following example
public void method(String ... strings)
can be called as
method()
method("s")
method("s", "d")
...
So your method can be called as
concat()
concat(new int[0])
concat(new int[0], new int[0])
...
This means that you can pass the method any number of int[] objects:
concat(new int[]{1,2});
concat(new int[]{1,2}, new int[]{3,4,5});
concat(new int[]{1}, new int[]{3,4,5,6}, new int[]{1,1,1,1,1,1,1});
Why this is useful? It's clear why :)
The ... is the most important part, it means you can have an unlimited amount of integers passed in and it is just accessed via the array, so you could call it as:
concat(1,2,3,4,5) or concat(1)
Most languages have this sort of feature, some call it var args others call it params.
varargs ("...") notation basically informs that the arguments may be passed as a sequence of arguments (here - ints) or as an array of arguments. In your case, as your argument is of type "array of int", it means arguments may be passed as a sequence of arrays or as an array of arrays of int (note that array of arrays is quite equivalent to multidimensional array in Java).
For example you have a method:
void functionName (Object objects...)
{
Object object1=objects[0];
Object object2=objects[1];
Object object3=objects[2];
}
You can use your method as:
Object object1,object2,object3;
functionName(object1,object2,object3);
Using Variable Arguments
The ellipsis (...) identifies a variable number of arguments, and
is demonstrated in the following summation method.
public static int[] concat(int[]... arrays)
Use method
concat(val1, val2, val3);
concat(val1, val2, val3, val3);

Can anyone explain the output that I am getting while compiling this program?

I executed the below mentioned code, when I got a strange output. Can anyone please explain why I am getting this output ?
Code:
public class Bar {
static void foo( int... x ) {
System.out.println(x);
}
static void foo2( float... x ) {
System.out.println(x);
}
public static void main(String args[])
{
Bar.foo(3,3,3,0);
Bar.foo2(3,3,3,1);
Bar.foo(0);
}
}
Output
[I#7a67f797
[F#3fb01949
[I#424c2849
Why are we getting the "[I#"/"[F#" prefixes and the 8 alphanumeric characters to follow, are they memory address ?
Java arrays have a toString() method that simply display the type of the array ([I), followed by an #, followed by the hash code of the array (7a67f797). This value is almost meaningless. And toString() is the method called on every object passed to System.out.println().
If you want to see the contents of the array, then use java.util.Arrays.toString(array).
float... is syntactic sugar for float[], so
System.out.println(x);
...is trying to output an array. So you're getting the default toString behavior of objects, rather than the values in the array.
To output the array, either loop through it, or use something like Arrays.toString:
System.out.println(Arrays.toString(x));
...and the 8 alphanumeric characters to follow, are they memory address ?
No, they're just the object's hash code (this is covered in the first link above).
Use this to see values in array.
System.out.println(x[0]);
System.out.println(x[1]);
....
System.out.println(x[3]);
1) foo( int... x ) is called varargs (variable arguments). Compiler replaces Bar.foo(3,3,3,0) with actual Bar.foo(new int[] {3, 3, 3, 0})
2) You are printing float and int arrays. They inherit toString from Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
[I and [F are class names for int[] and float[], try this
System.out.println(float[].class.getName());
output
[F

Double elements in Float arraylist after parsing numbers by numberFormat

I want to parse some Strings (they include some numbers) with same format but different number kind and set these number to their related array. for example having this string: " "positions":[[35.23,436.34],[23.5, 7.1]] I want to put these number into a float array named "this"! and for this string" "indices":[[23,4],[2,1]]" I want to put them into an integer array named "that"!
To do so, I've wrote a generic function with this declaration:
private <E extends Number> voidfunc(ArrayList<E> array, String JSON){
.
.
array.add((E) NumberFormat.getInstance().parse(JSON.substring(...)));
.
.
}
this works well and put numbers into array correctly but later, in somewhere in my app I get a "class cast exception. Can not cast Double to Float" trying to do this:
floatArray[i] = temp.get(i);
temp have defined as a float arraylist and have filled with above function.
can anybody tell me why it is so, and how can I solve that? I really appreciate that.
In your example, E is type parameter of generic method. This type is not known at run time, so cast to this type done with (E) is fake and compiler most probably reported warning at this line. JVM does not check type compatibility during this cast, so it is possible that value of incompatible type will get into the list. For example, value of Double type may be stored in List<Float>. Later, when you try to extract value form the list and cast it to Float, ClassCastException will occur.
You probably need to change your code like this:
private void func (ArrayList <? super Double> array, String JSON)
{
...
array.add (NumberFormat.getInstance ().parse (JSON.substring (...)));
...
}
ArrayList <Number> temp = new ArrayList ();
func (temp, json);
floatArray [i] = temp.get (i).floatValue ();
Try with:
floatArray[i] = ((Double) temp.get(i)).floatValue();

array-element:array-name in Java

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

Categories

Resources