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.
Related
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});
This question already has answers here:
How do I do a deep copy of a 2d array in Java?
(7 answers)
Closed 4 years ago.
I'm relatively new to Java, and I just learned this
import java.util.Arrays;
public class Foo {
private int[][] foo;
public Foo(int[][] arr) {
this.foo = arr;
}
#Override
public String toString() {
return Arrays.deepToString(this.foo).replace("],", "],\n");
}
public static void main(String[] args) {
int[][] p = { { 0, 0 }, { 0, 0 } };
Foo g = new Foo(p.clone()); // doesn't work with p nor p.clone()
System.out.println(g);
p[0][0] = 1;
System.out.println(g);
}
}
Here I create an object with a reference to another object, and I can alter the object from the outside since I have the reference to the thing I just passed as an argument to the constructor.
This, although I understand why it happens, seems counterintuitive to me. If I save something as an attribute of an object I expect the object to have a “private” copy not accessible outside.
And I tried with .clone() and doesn't solve it. So the question is...
How is this usually done? Do I need to write a few for loops inside the constructor to get every value out of the argument?
(Or is this a non-issue?)
This last part of the question is important, may be this is a non-issue. Or do people do “something” (a few loops to get a deep clone)?
The problem here is that java doesn't really have 2-D arrays. This:
int[][] x;
is an array of int arrays. It is not a 2D int array, though of course an array of int arrays does feel a lot like a 2D array. For most intents and purposes it iS a 2D int array, unless it isn't, and with clone, it isn't. The clone() impl of an array makes a new array and just copies each and every value, verbatim, into the new array. Which means that your array of int arrays is cloned, but the inner int arrays are not.
When treating int[][] as 'this is a 2D array', yeah, that is unintuitive. When treating int[][] as 'an array of int arrays', it is quite intuitive. You wouldn't expect an array of arraylists, when cloned, to also clone each individual arraylist either.
Soo.. how do you deep-clone an array of arrays (of arrays of arrays)? See How do I do a deep copy of a 2d array in Java? for lots of options :)
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.
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);
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".