I'm asking me if the initialization of array in Java is the same as C. In C you can't define the size of the array while the program is running. Is it possible in Java (or just right as concept)?
public int[] createArray(int size) {
return new int[size];
}
In my case I have to use an array and not an arraylist because I'm drawing a Polyline on a Panel
g.drawPolyline(xPoints[], yPoints[], n);
Thanks for help
You can't change array size once it's created,but you can use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) to copy the value of the array to another bigger array,don't worry about its speed,because it's built-in function and implemented with JNI,so it's very fast
C does not have the fundamental concept of an "array" as Java does; in C, you'd
malloc(some_size * sizeof(one_element))
and affect it to a one_element * (of course, that is a gross description).
In Java, arrays are equally dynamically allocated; if you know the size, at runtime, then you can, for an array of SomeType and of size someSize do:
final SomeType[] myArray = new SomeType[someSize];
In essence, it's quite the same; including the fact that in both cases arrays are NOT resizable, but with a huge difference on what happens if you specify an invalid index:
in Java, this leads to an IndexOutOfBoundsException;
in C, this is undefined behavior.
All in all, apart from the consequences of using "arrays" incorrectly, what goes in C and what goes in Java only really differs by the syntax to create the array to begin with...
As others have mentioned, you cannot do this. But instead you can use ArrayList (or any other List) and where needed, convert it to simple array, like this:
ArrayList<String> arrayList = new ArrayList<>();
String strings[] = (String[])arrayList.toArray();
In C you can't define the size of the array while the program is running. Is it possible in Java (or just right as concept)?
Yes you can define the size of an array at runtime, just not redefine it. This will create an object on the heap with either enough space to hold the required number of primitives (in case of a primitive array) or object references (think of them as pointers).
If you want to redefine the size of an array you'd need to create a new one and copy the old (System.arraycopy() or Arrays.copyOf(...)).
In my case I have to use an array and not an arraylist because I'm drawing a Polyline on a Panel
Well, you could still use a list and call toArray(...) on it. This also is an example of creating an array at runtime.
Since you want to eventually call Graphics.drawPolyline(...) you'd have to either maintain two List<Integer> or preferably a List<Point> and construct the x and y arrays internally out of that list.
Related
I want to know why an array created in Java static even when we use the new keyword to define it.
From what I've read, the new keyword allocates a memory space in the heap whenever it is encountered during run time, so why give the size of the array at all during definition.
e.g. Why can't
int[] array1=new int[20];
simply be:
int[] array1=new int[];
I know that it does not grow automatically and we have ArrayList for that but then what is the use of keyword new in this? It could have been defined as int array1[20]; like we used to do it in C, C++ if it has to be static.
P.S. I know this is an amateurish question but I am an amateur, I tried to Google but couldn't find anything comprehensive.
This may be an amateurish question, but it is one of the best amateurish questions you could make.
In order for java to allow you to declare arrays without new, it would have to support an additional kind of data type, which would behave like a primitive in the sense that it would not require allocation, but it would be very much unlike a primitive in the sense that it would be of variable size. That would have immensely complicated the compiler and the JVM.
The approach taken by java is to provide the bare minimum and sufficient primitives in order to be able to get most things done efficiently, and let everything else be done using objects. That's why arrays are objects.
Also, you might be a bit confused about the meaning of "static" here. In C, "static" means "of file scope", that is, not visible by other object files. In C++ and in Java, "static" means "belongs to the class" rather than "belongs to instances of the class". So, the term "static" is not suitable for describing array allocation. "Fixed size" or "fixed, predefined size" would be more suitable terms.
Well, in Java everything is an object, including arrays (they have length and other data). Thats why you cannot use
int var[20];
In java that would be an int and the compiler would be confused. Instead by using this:
int[] var;
You are declaring that var is of type int[] (int array) so Java understands it.
Also in java the length of the array and other data are saved on the array, for this reason you don't have to declare size of array during declaration, instead when creating an array (using new) the data are saved.
Maybe there is a better reason that oracle may have answered already, but the fact that in Java everything is an object must have something to do with it. Java is quite specific about objects and types, unlike C where you have more freedom but everything is more loose (especially using pointers).
The main idea of the array data structure is that all its elements are located in the sequential row of memory cells. That is why you can not create array with variable size: it should be unbounbed space vector in memory for this purpose, which is impossible.
If you want change size of array, you should recreate it.
Since arrays are fixed-size they need to know how much memory to allocate at the time they are instantiated.
ArrayLists or other resizing data structures that internally use arrays to store data actually re-allocate larger arrays when their inner array data
structure fills up.
My understanding of OP's reasoning is:
new is used for allocating dynamic objects (which can grow like, ArrayList), but arrays are static (can't grow). So one of them is unnecessary: the new or the size of the array.
If that is the question, then the answer is simple:
Well, in Java new is necessary for every Object allocation, because in Java all objects are dynamically allocated.
Turns out that in Java, arrays are objects, different from C/C++ where they are not.
All of Java's variables are at most a single 64bit field. Either primitives like
integer (32bit)
long (64bit)
...
or references to Objects which depending on JVM / config / OS are 64 or 32 bit fields (but unlike 64bit primitives with atomicity guaranteed).
There is no such thing as C's int[20] "type". Neither is there C's static.
What int[] array = new int[20] boils down to is roughly
int* array = malloc(20 * sizeof(java_int))
Each time you see new in Java you can imagine a malloc and a call to the constructor method in case it's a real Object (not just an array). Each Object is more or less just a struct of a few primitives and more pointers.
The result is a giant network of relatively small structs pointing to other things. And the garbage collector's task is to free all the leaves that have fallen off the network.
And this is also the reason why you can say Java is copy by value: both primitives and pointers are always copied.
regarding static in Java: there is conceptually a struct per class that represents the static context of a class. That's the place where static instance variables are anchored. Non-static instance variables are anchored at with their own instance-struct
class Car {
static int[] forAllCars = new int[20];
Object perCar;
}
...
new Car();
translates very loosely (my C is terrible) to
struct Car-Static {
Object* forAllCars;
};
struct Car-Instance {
Object* perCar;
};
// .. class load time. Happens once and this is referenced from some root object so it can't get garbage collected
struct Car-Static *car_class = (struct Car-Static*) malloc(sizeof(Car-Static));
car_class->forAllCars = malloc(20 * 4);
// .. for every new Car();
struct Car-Instance *new_reference = (struct Car-Instance*) malloc(sizeof(Car-Instance));
new_reference.perCar = NULL; // all things get 0'd
new_reference->constructor();
// "new" essentially returns the "new_reference" then
I've got a lot of old code with big double[][] arrays and I need to flatten in a double[] array for a new library usage.
I don't want to copy, is there a simple way to re-reference the array like in C?
It's impossible to do without a copy.
The memory with double[][] is not contiguous.
The "rows" in double[][] refer to double[] objects.
The memory occupied by double[] has to be contiguous.
No. This is not possible without a copy1.
Unlike a Nd array in C, where math is performed to map onto a single contiguous object (and thus a cast might work; but ask a C language lawyer), a "2d" array in Java is an Array (object) -of- Arrays (many objects). This extends for each additional dimension.
That is, a 2d array in Java can be though of as a double* [] in C, where each row/column of the secondary axis has been malloc'ed separately; and where accessing a cell requires two lookup operations, even if it still 'looks' like double[][] access.
1 Because Java does not allow operator (ie. []) overloading even trying to wrap 1d-to-Nd access no longer looks like that of an array, but rather that of a List/ArrayList. In any case this would still require the individual lookups underneath.
I know that when I initialize a char array:
I have to
char[] b= new char[5];
or
char[] b= new char[5]({1,2,3,4,5});
why not like
ArrayList<Charset> list = new ArrayList<Charset>();
initialize array :
char[] b = new char[5](); ?
Why they are different? Is it one of java philosophical nature or some reasons behind it ?
If you've ever used C, then the answer is fairly simple. In C, the way you create arrays is by allocating a static length of memory on the stack that is large enough to contain the number of elements, and point to the first element with a pointer - or dynamic length of memory on the heap, and point to the first element with a pointer.
int a[5]; //stack, static allocation
int* a = (int*)malloc(sizeof(int)*5)); //heap, dynamic allocation
And in C++, the second version was changed to this, obviously because it's more obvious what is happening:
int* a = new int[5];
And they took this type of array creation over to Java.
int[] a = new int[5];
Arrays don't really work like typical objects, hence why even creating them and manipulating them with reflection uses a different Array class in order to manipulate the object. (see http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html )
ArrayLists are different, because they're just everyday classes like most things in java, so you initialize them with an actual constructor call:
List<T> = new ArrayList<T>();
Basically, arrays and classes just work in different ways.
That's is simply design of Java. ArrayList and Arrays are two different things. No need to be same declaration.
I guess the guys who created Java wanted to keep a syntax close to the C syntax. In Java, arrays are minimalist low-level objects, so their case is a bit particular.
ArrayList is a container, it's similar as Vector in C++, it can add and remove elements, but array can't change its size
Arrays and ArrayList are used for different purposes. If you need a fixed size collection of objects then go for array but if you need dynamically growing collection of objects then go for arraylist. In some way compiler need to know about what is your need, hence the syntax is different.
In java is it possible and if not how to calculate in c?
if it's really array (not a pointer), you can do sizeof(arr)/sizeof(*arr)
In Java, the length of a primitive array is array.length, while the length of an ArrayList (and most other collections) is arrayList.size()
In C, the length of an array is sizeof(array) / sizeof(array[0]), but this is nearly useless since you can't pass arrays as arguments (they degenerate to pointers). The normal way to find the size of an array in C is to pass it as an extra argument to the function, or sometimes to terminate it with a sentinel value (eg. strings are \0 terminated)
There is no way to calculate that. in C (not C++, which has std::array and std::vector) an array is transmitted as its pointer, which you might increase by some offset. So you really don't know the runtime size of an "array", except by some conventions.
In particular for formal arrays, there is no way to know the size of the actual array passed
e.g. as void f(int arr[]) { /*...*/ } unless you give a static dimension.
Likewise, with an external array declared as extern int xarr[]; you cannot get its dimension with sizeof(xarr)/sizeof(xarr[0]).
In C, there is no way of calculating the size of array if you have only a pointer to it. You must store it in separate variable.
In fact you HAVE TO keep the size of an array in separate variable because you have to allocate memory if you want to use dynamic-size array.
And if you want to use fixed-size array you know it's size by the time you're writing your code so why not use #define, variable or const to store it?
Java is totally different language than C and the philosophy of programming is different-you should always keep that in mind.
In Java, you should use array.length, look here for example: http://www.roseindia.net/help/java/a/java-array-length.shtml
Simply, there is no possibility if you recieve only a pointer. That's why main has an argc argument. It defines the number of entries in argv. If you have an array "datatype" (actually the same as a pointer, but the behaviour depends on the context), you can use
int[] arr = new int[10];
sizeof(arr)/sizeof(int) // or whatever type is contained in ``arr``
How can I initialize an array of objects of a class in another class without hardcoding its size?
Use a List. The size does not need to be declared on creation of the List. The toArray() method will return an array representation of the list. There are multiple implementations you can use but the most popular tends to be ArrayList (though it is best to map the implementation to your particular situation).
Arrays have a fixed size after creation. The size doesn't need to be known at compile-time, but it does need to be known at creation time. For example:
public String[] createArray(int size) {
// Not hard-coded, but array is not expandable
return new String[size];
}
If you want a collection which can grow an shrink over time, look at the various List<E> implementations, such as ArrayList<E>.
Arrays are fixed in length. I would recommend using a Collection.
Here is an article on collections:
http://en.wikipedia.org/wiki/Java_collections_framework
With these, you can add elements by using an Add() command or something similar.
As mentioned in the previous answers, an ArrayList or List are collections.
Object[] will always be fixed size. If you need a variable length collection, try ArrayList, LinkedList, or one of the many others.
Pick the collection carefully, since they all have different performance aspects.
For mutable arrays other container objects are used.
When using a set of objects, an ArrayList or Vector object is used.
You can also store objects with an object key e.g. "Name" = "Ben" instead of [0] = "Ben".
Vector v = new Vector();
for(int i = 0; i < 100; i++){
Object o = new Object();
// init object
v.addElement(o);
}
for(int i = 0; i < 100; i++){
Object o = v.elementAt(i);
// manipulate object
}
Now you have an arbritairy list of object of undefined length.
Size found by using vector.size() method.
java.util package is required and part of J2SE 1.3 and higher.
As noted elsewhere, an array object has a fixed size. If there's some reason you must use an array, you can use one or both of these techniques:
Make it the larger than you need, leaving the unused
entries null. You may want to keep a "slotsUsed" variable.
When the array gets too small, make a bigger one and copy the
contents into it.
These are both used inside ArrayList.
You can create a new array and initialize it like this.
String[] strArray = {"Initialize","Array","Like","This"};
If you want an array with a dynamic size I would recommend using an ArrayList.
If you want an array of primitive instead of objects, you can use Trove4j. Otherwise use an ArrayList, or CopyOnWriteArrayList to wrap an array. There are other List implementations but these do not act like arrays for access time.
Sometimes it is useful, in case you know an upper bound of the objects your application needs,
to declare the size of an array as
static final int ARRAY_SIZE = 1000;
This goes near the beginning of the class so it can be easily changed.
In the main code instantiate the array with
Object[] objects = new Object[ARRAY_SIZE];
Also in case the array you want to use has the same size as another array consider using
Object[] objects = new Object[other_objects.length];