Array as parametar [duplicate] - java

This question already has answers here:
Java array initialization within argument list
(4 answers)
Closed 7 years ago.
I don't understand, and can't find on google how do I call my method, whose parameter is an array?
private static void printArray(double a[],int p){
int count[]=new int[p];
for(int i=0;i<a.length;i++){
for(int j=0;j<p;j++){
if((a[i]>=100/p*j) && (a[i]<100/p*(j+1))){
count[j]++;
for example, how do I call this method in my main method:
I tried printArray({1,2,3,4,5},5); and it's not working or printArray([10],5); but still doesn't work?

You would first need to create an array. Like you did here:
int count[]=new int[p];
In your example something like
double myArray[] = {1,2,3,4,5};
Then you would pass the variable name to your method like:
printArray(myArray, someInt);
Hope this helps.

The issue with your calls is:
printArray({1,2,3,4,5},5); - {1,2,3,4,5} as a parameter is not recognized. You need to create an array which is of type double.
printArray([10],5); - [10] is also not recognized by the compiler and is not the correct way to pass double[].
This is how to initialize an array inline in java:
new double[]{1,2,3,4,5}
So, this is how you call it:
printArray(new double[]{1,2,3,4,5},5);

you can call your method like this, if the method is in the same class with method main.
double[] arr = {1,2,3,4,5};
printArray(arr,5);

[10] is not a variable. When you pass an array you do not need brackets. Just the variable name. For example:
double array1[] = {10,12,13};
printArray(array1);

Related

why I need 'new' for array parameter? [duplicate]

This question already has answers here:
Passing directly an array initializer to a method parameter doesn't work
(3 answers)
Closed 2 years ago.
int add(int[] scores){ ... }
-------------------------------
int result = add({1,2,3}); //wrong
int result = add(new int[] {1,2,3}); //correct
I know I have to code like this but
why we must put 'new int[]' for parameter??
The array initializer syntax ({1, 2, 3}) can only be used in certain circumstances:
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
In other circumstances, you would need to use an array creation expression (e.g. new int[] {1, 2, 3}).
This is just how the language is specified. It could be different, but it's not.
As it has been pointed out, the array initialize can only be used in variable declarations.
You might want to use varargs in you example like that:
int add(int... scores){ ... }
You can call it in two ways:
int result = add(1,2,3);
int result = add(new int[] {1,2,3});

Why I can't declare an array and then assign value in this fashion? [duplicate]

This question already has answers here:
Array initialization syntax when not in a declaration
(4 answers)
How do I declare and initialize an array in Java?
(31 answers)
Closed 4 years ago.
Why when I try to initialize the array like that it gives me an error
package practicejava;
class Test {
public static void main(String[] args) {
int[] array;
array ={};
}
}
Why the following code shows me an error?
Change as follow:
int[] array;
array = new int[]{};
Your current way of assigning the array is invalid.
you have to declare array size in array like as below
array = new int[5];
The array needs to be declared on the same line of code as:-
int[] array = new int[]{...};
The first line of your code that is:-
int [] array = {...}
This line is allowed by Java and is just a shorthand notation for the above declaration. Note that, this is only allowed if the declaration and initialization of the array is done simultaneously (the allocation of array is handled internally and is done accordingly to the number of elements).
The line
int [] array;
just creates a reference in the stack which is null that is it doesn't point to anything.
But, when you do array = {...}, it is no longer valid as the memory needs to be allocated prior to initialization. Java does not handle such initialization internally.
So, it is recommended to initialize
array = new int[]{...}
instead.

How to set array elements after I have initialized it? [duplicate]

This question already has answers here:
Initializing an array after the declaration
(4 answers)
Closed 6 years ago.
I am looking for a simple way to set the elements of an array after it is initialized. I have tried this :
package com.ehsan.app;
public class Main {
public static void main(String[] args) {
int[] test = new int[6];
test = {1,2,3,4,5};
}
}
However compiling this gives error :
Error:(7, 16) java: illegal start of expression
Error:(7, 17) java: not a statement
Error:(7, 18) java: ';' expected
Error:(9, 1) java: class, interface, or enum expected
I can use this way to put values in the array:
test[0] = 1;
test[1] = 2;
test[2] = 3;
test[3] = 4;
// and so on.
I am just looking for a simple way to do that.
Edit
I know I can use this :
int[] test = {1,2,3,4};
But what I want is a simple way to put values in array after its initialization.
And one another thing : I am not looking for loops!
Edit
The answer #Python gave was what I was looking for!
You can simply do this by using Arrays's static method in one line:
Integer[] test = new Integer[10];
Arrays.<Integer>asList(1,2,3,4,5,6,7).toArray(test);
Note: using 'int' is also fine but then you to add explicit casting (int[])
If you want to initialize an array, try using Array Initializer:
int[] test = new int[6];
int[] test = {1,2,3,4,5,6};
OR
int[] test = new int[]{1,2,3,4,5,6};
Initialize using a for loop:
for(int i=0;i<test.length-1;i++){
test[i]=i;
}
this will make the test array have, 0,1,2,3,4,5 as its contents;
I believe there is no other way than having a loop to populate your already-instantiated array.
However, you don't need to write the loop by yourself:
System.arrayCopy() does the work. And one day JVM may decide to do something like memcpy to do the work, by using such kind of built-in functions, you may benefit from such JVM change without change in your source code.
After initializing you can't assign values all at once,
you can do it this way :
test[0]=1;
test[1]=2;
and likewise..
hope this will help

Array declaration in main method [duplicate]

This question already has answers here:
Difference between int[] array and int array[]
(26 answers)
Closed 8 years ago.
I was reading and faced with interesting look of main method which I didn't see before. Is there any difference between
public static void main(String[] args)
and
public static void main(String a[])
As I see applying either of them gives me the same output
public static void main(String a[]){
List <Integer> li = new ArrayList <Integer>();
ListIterator <Integer> liItr = null;
li.add(1);
li.add(2);
li.add(3);
li.add(4);
li.add(5);
li.add(6);
li.add(7);
liItr = li.listIterator();
System.out.println("Elemnets in forward direction");
while(liItr.hasNext()){
System.out.println(liItr.next());
}
System.out.println("Elements in backward direction");
while(liItr.hasPrevious()){
System.out.println(liItr.previous());
}
}
}
P.S. I consider myself as a beginner of Java. If someone could highlight giving me some explanation on that it would be nice
From http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.2
The [] may appear as part of the type at the beginning of the
declaration, or as part of the declarator for a particular variable,
or both.
For example:
byte[] rowvector...
This declaration is equivalent to:
byte rowvector[]...
BTW, not many realize that unfortunately this rule affects also Type methodSignature pair, not only Type variable. So something like
int giveMeArray()[]{
// ^^^^^^^^^^^^^ - method signature
return new int[10];
}
is also valid Java code.
Anyway this way of declaring array can be useful if you would like to create... lets say 2 and 3 dimensional arrays. So instead of
int[][] arr2d;
int[][][] arr3d;
you can just write
int[][] arr2d, arr3d[];
// ^^-additional dimension
No, there's no difference. The only difference is the array declaration:
String[] args
vs
String a[]
Both are valid.
From Java Language Specification. Chapter 10. Arrays. 10.2. Array Variables. (emphasis mine):
Example 10.2-1. Declarations of Array Variables
int[] ai; // array of int
short[][] as; // array of array of short
short s, // scalar short
aas[][]; // array of array of short
Object[] ao, // array of Object
otherAo; // array of Object
Collection<?>[] ca; // array of Collection of unknown type
The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.
For example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
No there isn't a difference. See also http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html which states this: "You can also place the brackets after the array's name:", but suggests it is bad form.
String[] args is as valid as String args[] and as String a[].
Java has no restriction regarding arguments naming and authorizes both styles of array declaration syntaxes (brackets after or before the variable name) => Matter of taste.

I get these weird characters when I try to print out a vector element! [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I'm using Netbeans.
When I run the program below, I get this as output [I#de6ced! How come?
import java.util.Arrays;
import java.util.Vector;
public class Test {
public static void main (String[] args) {
int[] a = new int[1];
a[0] = 5;
Vector<Integer> a1 = new Vector(Arrays.asList(a));
System.out.println(a1.elementAt(0));
}
}
I also tried working around it but then I got a
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Integer
at TopCoder.Test.main(Test.java:13)
Java Result: 1
public static void main (String[] args) {
int[] a = new int[1];
a[0] = 5;
Vector<Integer> a1 = new Vector(Arrays.asList(a));
int b = a1.elementAt(0); /* EXCEPTION THROWN HERE */
System.out.println(b);
}
[I#de6ced can be broken down as:
- [ an array
- I of integers
- de6ced with this reference hash-code (which, in Sun Java, is basically the reference)
toString() for Object returns somethine like ClassName#HashCode, which is exactly what you're seeing happen here just with the (rather wierd) primitive-array classes.
The problem is that the wrong type is being inferred by the <T> List<T> asList(T...) method. Change your code to use Integer[] instead of int[]. This is a consequence of int being primitive, but int[] is an object.
You can see this directly:
System.out.println(Arrays.asList(new int[]{5}));
=> [[I#some reference
System.out.println(Arrays.asList(new Integer[]{5}).get(0));
=> 5
Integer[] a = new Integer[1];
a[0] = new Integer(5);
List list = Arrays.asList(a);
System.out.println(list.get(0));
The above works as you would expect.
So it looks like the "int" array is treated like an Object and not an array of Integers. In other words auto boxing doesn't seem to be applied to it?
I think I have figured out what was happening:
int[] a = new int[1];
a[0] = 5;
We now have an array of int.
Vector<Integer> a1 = new Vector(Arrays.asList(a));
The problem is in the way you are calling Arrays.asList.
The signature for asList is "public static <T> List<T> asList(T... a)". It does not apply with T == int because int is not an object type. And it cannot match with T == Integer because the base type of the array a is int not Integer. What is actually happening is that T is binding to int[], and Arrays.aslist(a) is returning a List<int[]> with one element that is the value of a!!!
Then you create a Vector from the List and get a Vector with one element ... the original int[] that was assigned to 'a'.
System.out.println(a1.elementAt(0));
Finally, a1.elementAt(0) fetches the int[], and you end up calling the Object implementation of the toString() method.
A couple of important lesson to learn from this:
it is a bad idea to mix raw types and
generic types as you do on the line
that declares a1, and
it is a bad idea to ignore, or turn
off the compiler's generic type-safety
warnings
It looks like the int's are becoming Integers using autoboxing so you are getting an object reference instead of the value. Still seems weird as it should call the correct toString and end up with "5".

Categories

Resources