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

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

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 access the subclass's Instance variable using the Array of Object? [duplicate]

This question already has answers here:
raw cannot be resolved or is not a field
(3 answers)
Closed 6 years ago.
I want to access the variable 's' using the array of objects 'arr'? Please refer the code snippet.
public class Array_Chp3 {
public static void main(String[] args) {
Array_Chp3[] arr = new Array_Chp3[3];
arr[0] = new str(); // when used this line instead of the below line , getting the error "s cannot be resolved or is not a field"
//arr[0] = new Array_Chp3(); // when used this line instead of the above line, getting the error s cannot be resolved or is not a field
str obj = new str();
System.out.println(arr[0]);
System.out.println(arr.length);
System.out.println(arr[0].s); // How to access the variable 's'?
}
}
class str extends Array_Chp3{
public String s = "string123 # str";
}
Error Message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
s cannot be resolved or is not a field
at Array_Chp3.main(Array_Chp3.java:17)
Your array is an array of Array_Chp3. That means that you decided that elements of this array are instances of Array_Chp3. You don't really care what concrete type they have, as long as they are instances of Array_Chp3.
What you store in its first element is a str instance. That's fine, since a str is a Array_Chp3 (it extends Array_Chp3).
But since the type of the array is Array_Chp3[], the compiler can't guarentee that its element are all instances of str. All it can guarantee is that they're instances of Array_Chp3.
You know that it's a str though, so you can tell the compiler: trust me, I know it's in fact a str. That is called a cast:
System.out.println(((str) arr[0]).s);
But it shows a design problem. If you need the elements to be instances of str, then the array should be declared as an array of str.
If you know it is str you can cast it like this:
System.out.println(((str)arr[0]).s);

Array as parametar [duplicate]

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

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