Array Creation Method with a 'name' Parameter: Scope Error - java

I'm creating some helper methods for a class project. One of the methods I wanted to create was a simple create an array of type int, called 'name', of 'size' size. The problem arises in the body of the method where I try to use the 'name' parameter to create the array.
public int[] createArray(String name, int size){
int[] name = new int[size];
}
In addition to getting a "Variable 'name' is already defined in the scope." error, I think the issue is that I can't use a variable in the construction of an array. If that's the case, should I not be using 'String name' as a parameter here? Is there some sort of parse/conversion I can do? Conclusively, what do I have to use/do to pass a parameter from the method call into "int[] _____ = new int[size];"?
I'll probably just make the 2 arrays I need normally in the main method, but I wanted to learn what I was doing wrong.
Best,
Corey

Rename you variable name in
int[] name = new int[size];
to
int[] otherName = new int[size];
and it should work fine. Since there is another variable with the same name in the scope because of String name used as your argument to the method.
Also in case you want to use the parameter to actually name your array variable, then you would probably be trying to modify the source code during its runtime, which you can't. That said, the variable String name doesn't seem useful in the method anymore.

What you try to do is impossible (unless you resort to "reflection" which I wouldn't recommend to a relative beginner).
You want to create an array variable with a name that you want to decide at runtime. You want to do something like
int[] array1;
int[] array2;
createArray("array1", 17);
createArray("array2", 25);
The variable names array1 and array2 exist at compile time. When the program runs, they are no longer available (to normal Java code). The "array1" and "array2" parameters that you want to pass to the createArray() method are strings, and the Java runtime will not associate the characters in these strings with the array variables.
The Java way for the thing you tried to achieve is:
int[] array1 = createArray(17);
int[] array2 = createArray(25);
private int[] createArray(int size) {
return new int[size];
}

Related

Is it an Anonymous Array if the resulting array is assigned to a variable

(I am studying for the Java Associate Exam OCJP 7)
A question asked to select examples of illegal initializations.
One of the answers was:-
int [] k= new int[2]{5,10};
The explanation said that when creating an anonymous array it was illegal to specify the size of the array.
From what I know this is NOT an anonymous array as it is named "k".
Calling a method such as :-
operateOnArray(new int[]{5,10});
Would have been an example of an anonymous array since it is not declared.
I can see that the "2" makes it illegal - but that does not make it anonymous,
Please can someone advise me?
Mmmm... from what I've been taught (and also from what I've read), the definition of an Anonymous Array is: "Array without any name, it is an array just for create and use it". And since it does not have any name, you should not be able to reuse that array.
The best references I had when I prepared for the OCJP was:
anonymous int array : new int[] { 1, 2, 3, 4};
anonymous String array : new String[] {"one", "two", "three"};
anonymous char array : new char[] {'a', 'b', 'c');
You can notice that (and also you already know) these type of arrays have the creation and initialization at the same time (as you initialize them in the same line you create them using the new() keyword without assigning to any variable and you would not be able to reuse it later).
So, from what you have mentioned, when you assign an array to a variable, even when you create it and initialize at the same line, it is being assigned to a variable so it is able to be reused later, it is not anonymous, it can be referenced, so I wonder why in the examples of "anonymous arrays" you see something like:
int [] k= new int[2]{5,10};
Anonymous means "not known by name" which is not the case in the line you specified since the array is assigned to a variable called "k". However, this one shows the property of anonymous array-object creation which is pointed by a reference variable "k", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created...
When I prepared for OCJP 7 I read many articles from this page, I would recommend it to you to go deeply in Java in the future :)
Reference: http://javarevisited.blogspot.com/2012/01/anonymous-array-example-java-create.html
You can find also good examples and articles there :)
I think it will be like an anonymous method...
The anonymous array would be like myListView.setAdapter(this, new String [] {"Peter", "Paul", "Marry"});
Where the (new String [] {"Peter", "Paul", "Marry"}) is the anonymous array :-)
So a normal (not anonymous) array would be decleared (maybe in onCreate) like
String [] array = new String []...
While the anonymous one won't be decleared before usage...
It is not so clear what exactly is the question, but I get the point clearly that there is a confusion with regards how to correctly use the concept of an anonymous array in Java. You can only declare an anonymous array as an argument to a function. All else attempts to declare anonymous array not in this context, failed. This quick video shows it:
anonymous array as argument to function
If you see this part of the code:
new int[2]{5,10}
in the first declaration and then
new int[]{5,10}
from the second declaration. It's basically the same
So, a declaration like:
new int[]{5,10}
is an anonymous array, no matters what happen next. If you do not set it to a variable, it remains anonymous.

extend the array-class (note 'array' is in its singular form. I don't mean the Arrays.java )

If I declare x like this int[] x, then x is an object, isn't it? Which means int[] is a class?
Can I extend that class (for various reasons)?
I tried
class Foo extends int[]
{
}
But that's not working. Any idea?
Thanks
You cannot extend arrays in Java. They're these strange pseudo-class things that act somewhat similar to objects (have methods/fields, etc.) but aren't really. If you're trying to make a custom array, have you looked at the Collections API? That includes things like ArrayLists (arrays with variable lengths), which are pretty useful.
EDIT: If you need an array, use the "toArray()" method that all Collections have.
You can not extend int[] or any other array in Java. It is object but it isn't something you can extend like normal class in java.
int is primitive and you create array of ints using int[]
JComponent is class and you create array of JComponents using JComponent[]
You can extend JComponent class or any other non final class and create arrays of those by just adding [] to the end of variable declaration.
class Foobar { .... }
Foobar foobar = new Foobar();
Foobar[] foobarArray = new Foobar[10]; // size 10
class BiggerFoobar extends Foobar {...}
BiggerFoobar[] biggerFoobarArray = new BiggerFoobar[5];
An int[] is actually an array. It's not an object per se but a variable capable of holding many values of the same type and allowing quick access to them based on an index.
Funny tough, Oracle's documentation describes an array (located under the Variables category) as:
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.
int[] it's not an actual class type so you have no means of extending it. If you trully need to do this, you can extend any of the objects implementing the List interface (ArrayList for example) or that you implement the List interface yourself with a custom object.
If you want to turn a collection into an array, try something like this:
List<Integer> intList = new ArrayList<Integer>();
//Operate with your list
Integer[] arr = intList.toArray(new Integer[intList.size()]);
An int is a data type not an object.
Integer is an object, however you cannot extend that either because it is final.
I think you maybe need to re-think what exactly it is you are trying to do it, there is probably a different way.

referencing class variable to a local variable

why do some people make a new reference in method to a field variable?
public class Foo {
int mFoo[] = {1, 2, 3};
void method() {
int foo[] = mFoo; // WHY not just use mFoo?
print(foo[0]); // WHY not just use mFoo?
}
}
It can be a good idea if for example, at another place of your code, you change the value of mFoo. Especially in a multithreaded context, you would want to ensure you're still working on the right data.
It used to be the case (and still is with Java ME AFAIK) that loading a field into a local variable and using it multiple times was faster than access a field multiple times.
However, today using a local variable this way can confuse the JIT compiler and using a local variable this way can be slower.
It depends on your goal. If you want to modify whatever Object was passed in as a parameter you would not make a new instance of the type of the referenced Object.
Otherwise you would make a new instance which would you could modify freely without worrying about modifications to the passed in Object. This is commonly used in multi-threaded applications.
There's an accepted answer already, but the use makes more sense in this context:
private Class<?> clazz = ...;
public void foo() {
Class<?> current = clazz;
while (current != Object.class) {
// do some stuff.
current = current.superclass();
}
}
In this example you are constantly re-assigning "current" to a new value. Imagine the side effect without the variable, and if you kept doing:
clazz = clazz.superclass();
You'd be changing the field in the object itself, not locally to your method, so repeated calls to "foo" would not exhibit the behavior you are expecting.
It just doesn't make sense if you use just like this:
int[] local = somethingElse;
... // changes to local will reflect on somethingElse
It would make sense if a real copy would be done like:
int[] local = Arrays.copyOf(somethingElse,somethingElse.lenght())
... // changes to local will not reflect on somethingElse
The copy can prevent changing the elements that you will need on your method invoking other methods or by other Threads interference. In case that you have for example a method that changes this elements invoked at the same time you are using them. So, you can make a copy and work with them without being concern about the modification applied to it.
A test can be done with the following code:
int[] test = new int[] {1,2,3};
int[] test2 = Arrays.copyOf(test,test.length);
test2[0] = 9;
System.out.println(Arrays.toString(test));
In case of primitive types like int you're coping the values, not pointer, so your original array is still untouched after invoking method "print". It doesnt hold though for arrays

constructor calling in array creation

int[] a=new int[4];
i think when the array is created ..there will be
the constructor calling (assigning elements to default values)
if i am correct..where is that constructor..
No, there is no such thing. Primitive array elements are initialized to the default primitive value (0 for int). Object array elements are initialized to null.
You can use java.util.Arrays.fill(array, defaultElementValue) to fill an array after you create it.
To quote the JLS
An array is created by an array creation expression (§15.10) or an array initializer (§10.6).
If you use an initializer, then the values are assigned. int[] ar = new int[] {1,2,3}
If you are using an array creation expression (as in your example), then (JLS):
Each class variable, instance variable, or array component is initialized with a default value when it is created
No, there is no such constructor. There is a dedicated opcode newarray in the java bytecode which is called in order to create arrays.
For instance this is the disassembled code for this instruction int[] a = new int[4];
0: iconst_4 // loads the int const 4 onto the stack
1: newarray int // instantiate a new array of int
3: astore_1 // store the reference to the array into local variable 1
From a conceptual level, you could see the array creation as a array constructor, but there is no way for a programmer to customize the constructor, as array types have no source code, and thus can't have any constructors (or methods, by the way).
See my answer here for a conceptual view of arrays.
Actually, creating arrays is a primitive operation of the Java VM.

What does "public Weatherman(Integer... zips) {" mean in java

I am trying to read some Java code from a tutorial, I don't understand the line:
public Weatherman(Integer... zips) {
I don't understand what the ... represents if it was just (Integer zips) I would understand that there is a variable of class Integer called zips. But the ... are confusing me.
Those are "varargs," syntactic sugar that allows you to invoke the constructor in the following ways:
new Weatherman()
new Weatherman(98115);
new Weatherman(98115, 98072);
new Weatherman(new Integer[0]);
Under the covers the arguments are passed to the constructor as an array, but you do not need to construct an array to invoke it.
That’s a “vararg”. It can handle any number of Integer arguments, i.e.
new Weatherman(1);
is just as valid as
new Weatherman();
or
new Weatherman(1, 7, 12);
Within the method you access the parameters as an Integer array.
You are seeing the varargs feature of Java, available since Java 1.5.
zips is an array of Integer inside the constructor, but the constructor can be called with a variable number of arguments.
From the Java tutorials:
You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
public Polygon polygonFrom(Point... corners) {
int numberOfSides = corners.length;
double squareOfSide1, lengthOfSide1;
squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x)
+ (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
lengthOfSide1 = Math.sqrt(squareOfSide1);
// more method body code follows that creates
// and returns a polygon connecting the Points
}
You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.
If I remember good it is used when there is a variable number of parameters

Categories