Java array pass without reference - java

I am trying to pass an array without using a reference, but directly with the values :
public static void main(String[] args){
int[] result = insertionSort({10,3,4,12,2});
}
public static int[] insertionSort(int[] arr){
return arr;
}
but it returns the following exception :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token ")", delete this token
When I try the following code , it works , can anybody please explain the reason ?
public static void main(String[] args){
int[] arr = {10,3,4,12,2};
int[] result = insertionSort(arr);
}
public static int[] insertionSort(int[] arr){
return arr;
}

It has to be
int[] result = insertionSort(new int[]{10,3,4,12,2});
{10,3,4,12,2} is a syntactic sugar for array initialization, which must go with the declaration statement like the one in the following -
int[] arr = {10,3,4,12,2};
Something as follows is not allowed too -
int[] arr; // already declared here but not initialized yet
arr = {10,3,4,12,2}; // not a declaration statement so not allowed

insertionSort({10,3,4,12,2})
is not valid java because you don't specify a type in your method call.
The JVM does not know what type of array this is. Is it an array with double values or with int values?
What you can do is insertionSort(new int[]{10, 3 ,4 12, 2});

int[] array = { a, b, ...., n } is a shorthand initialization - you have to write:
int[] result = insertionSort(new int[]{10,3,4,12,2});
to initialize it anonymously.

Nothing much to add to what others said.
However I believe the reason why you should use new int[]{10,3,4,12,2} (like others stated) and Java doesn't let you use just {10,3,4,12,2} is that Java is strong typed.
If you just use {10,3,4,12,2} there is no clue of what the type of the array elements can be. They seem to be integers, but they can be int, long, float, double, etc...
Well, actually it might infer the type from the method signature, and fire a compile error if it doesn't fit, but it seems complicated.

Related

How to enter one dimensional array filled with unknown values of variable

I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)

Accessing static constant arrays from Jtwig template

So, I simply cannot gather access to values in constant static arrays.
Let this be an array in my code:
public static int[] MY_ARRAY;
And this is how i trying to access that array:
{{ constant("com.package.configs.MainConfig.MY_ARRAY")[0] }}
This attempt leads to an error:
java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
at org.jtwig.value.convert.collection.ArrayToCollectionConverter.convert(ArrayToCollectionConverter.java:11)
at org.jtwig.value.convert.CompositeConverter.convert(CompositeConverter.java:15)
at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:19)
at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:12)
at org.jtwig.render.expression.CalculateExpressionService.calculate(CalculateExpressionService.java:14)
...
I also tried to assign a constant to variable first, then accessing it, but nothing changed.
Previously, in an older versions of JTwig i was able to access any public static field of a object that i passed to the model. But now such fields are being ignored.
The version i am using is 5.86.0.
Any idea on how to beat this, or at this moment it's technically impossible?
The exception
java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
means the array MY_ARRAY is an int-type array, and int is a primitive, thus it's not a sub type of Object, so you can not cast it to an Object-type array.
In this case, you can change MY_ARRAY's Signature to public static Integer[] MY_ARRAY.
Integer wraps the int value in an Object.
This is illustrated by the following example:
public static void main(String args[]) {
int[] arr = new int[5];
Integer[] arrI = new Integer[5];
test(arr); // error:The method test(Object[]) in the type Demo is not applicable for the arguments (int[])
test(arrI); // ok
}

Failed to pass array as parameter in java

I have a method doSomething() which accept Array as parameter. When I pass array like bellow:
package org.my;
public class ArrayMistry {
public static void main(String ... args) {
doSomething({1,2});// Compilation Error
}
public static void doSomething(int[] params) {
}
}
I am getting compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: Syntax error on token "doSomething", # expected before
this token Syntax error, insert "enum Identifier" to complete
EnumHeader Syntax error, insert "EnumBody" to complete
BlockStatements
at org.my.ArrayMistry.main(ArrayMistry.java:6)
Note:
if I pass as bellow then its OK:
public static void main(String ... args) {
int[] p = {1,2};
doSomething(p);// no Error
doSomething(new int[]{1,2});// no Error
}
Arrays are passed by reference. You need to create an array object with [1,2] and pass the reference of that created object to dosomething. The new keyword allocates space for the creation of this int array.
int[] arr = new int[]{1,2};
doSomething(arr);
It's because you aren't declaring {1, 2} as a new array. It must be declared as new int[]{1,2} to function properly, otherwise you are not creating an array.
You have to make an array to pass into a method because you initialized the method that way. The reason this doSomething({1,2}); doesn't work is because the array has not been initialized and {1, 2} is not an array, it is just some numbers in a parenthesis. if you wanted to send an array you have to do something like this
int[] p = {1,2};
doSomething(p);
Your method doSomething() specifically accepts an array of integers as its parameters.
Note in both cases where it worked, you either passed an existing array, or created a new one when passing it in.
In your original example, you are passing an arbitrary set of numbers with no memory reserved, or type specified.
Another way to solve the problem is by passing a reference as a parameter to the function like this:
doSomething(new int[]{1,2});

Accepting any array as a parameter

I am trying to get getIntArrayString to accept parameters given to it, unlike abc.getAverage which uses the field testArray.
edit: Forgot to ask the question.
how would I be able to send parameters such as test1 to getIntArrayString()?
private int testArray;
public static void main(String[] args)
{
int[] testArray = new int[]{2,4,6,8,9};
ArrayHW abc = new ArrayHW(testArray);
System.out.printf(abc.getAverage());
int[] test1= new int[]{3,4,5,6,7};
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
int[] test1= new int[]{3,4,5,6,7}
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
}
I'm assuming you have a method named getIntArrayString inside another class. If you want to send the values of test1, the method getIntArrayString must have a parameter of test1's datatype. For example,
public int getIntArrayString(int [] x)
{
}
You should review your knowledge of methods.
Having two variables called testArray may seem a little confusing, but it's not syntactiacally wrong. However, it's less confusing to read your code if you don't, and even better if you remove any unused variables.
You are not posting any error messages, but I suppose you can't compile because you haven't declared any variable "ahw", and ahw.getIntArrayString() produces a compiler error.
In general, in order to be able to send a parameter of type int[] to a method it would be declared like this:
public String getIntArrayString(int[] intArray) { ... }
And you would call it like this
System.out.println(x.getIntArrayList(test1));
where test1 is an int array as declared in your own code.

Set array method on java

I have a class arrayFun with the variable
int[] _array;
I have a method setArray:
public void setArray(int [] array)
{
_array = array;
}
Is my set method implementation correct ?
2).How can I use this method in other class with main ?
I've tried some ridiculous options like:
arrayFun A = new arrayFun(some_constructor_values);
A.setArray(1,2,3,4,5);
That option of course doesn't work...
Try
A.setArray(new int[]{1,2,3,4,5});
Another way to solve this declare the argument as a "varargs" argument as follows:
public void setArray(int ... array) {
_array = array;
}
and then this will work:
A.setArray(1, 2, 3, 4, 5);
You can do the same with a constructor argument.
While I have your attention, it is important that you learn the Java naming conventions, and learn to follow them strictly.
A class name should always start with an uppercase letter
A variable name should always start with a lowercase letter ... unless it is a static final constant.
Using an underscore as a prefix generally frowned on.
For more information, read the Java Style Guidelines.
So your example class should look like this:
public class ArrayFun {
private int[] array;
public void setArray(int ... array) {
this.array = array;
}
}
and should be used like this:
ArrayFun a = new ArrayFun();
a.setArray(1, 2, 3, 4, 5);
You can use this instead
public void setArray(int... array) { _array = array; }
// later
ArrayFun a = new ArrayFun(some_constructor_values);
a.setArray(1,2,3,4,5);
Unless you take a copy of the array, you will be using the same array in the caller and callee.
What you're asking to do doesn't really make sense. Also, why use a function to "set the array", why not just set the array directly:
_array = newArray
You can also set an array's values like this:
int[] array = {1,2,3,4,5};
Your method's signature is :
public void setArray(int[] array)
So it accepts only one argument that is of type array of integers.
But in your method call, you are calling it as:
A.setArray(1,2,3,4,5);
In this you are passing 5 arguments to the method. So it does not match any method with 5 arguments. Thats why it does not work.
You should pass one array of integers.
You can do it in various ways :
int myArr[] = {1,2,3,4,5};
A.setArray(myArr);
or
A.setArray(new int[]new int[]{1,2,3,4,5});
Setting array the way you did is fine. But what you are setting from A.setArray(1,2,3,4,5); will throw you error saying "Method setArray(int,int,int,int,int) is not found".
You can do something like int[] ar = { 1, 2 };
a.setArray(ar);

Categories