Array or ArrayList? - java

Here is an exercise:
Write an algorithm that declares and fills an array of 7 values numerics, bij putting the values to 0.
In Python I have to do this:
note = []
for i in range(7):
note.append(0)
print( note )
I have tried below in Java... I am obliged to use an arrayList?
I would like the do with an array empty.
int[] notes;
for(int i=0;i<7;i++){
notes.add(0);
}

try this:
int[] notes = new int[7];
for(int i=0;i<7;i++){
notes[i] = 0;
}

When declaring your notes array you must initialize it and specify the length of it. If not it will throw a compilation error. Proceed as follows:
int[] notes = new int[7]; //Declare the size of the array as 7
for(int i=0;i<7;i++){
notes[i] = 0; //Iterate the positions of the array via the variable i.
}
If you want to use an ArrayList:
List<Integer> notes = new ArrayList<Integer>(); //You don't have to define the length.
for(int i = 0; i < 7, i++) {
notes.add(0);
}

You can also do like this.
Arrays.fill(notes, -1);// But notes has to be declared.
or
int[] notes = {0,0,0};

For the special case of int and a desired value of 0, you don't even have to write out the loop assignment. You just need this:
int[] notes = new int[7];
This will create an array of ints, each with the Java default value of 0.

You need to use an assignment operation.
notes[i] = 0;

Another option - using streams:
int[] notes = IntStream.range(0, 7).map(i -> 0).toArray();
But if you need exactly 0, you can simply do it like:
int[] notes = new int[7]; // but it for 0 only

Related

Find the width of a 2D array with a zero length

Imagine an array defined as follows:
int n = 10;
int[][] arr = new int[0][n];
Let's say this array is passed into several methods without preserving n. Can we obtain n from this array?
arr[0].length certainly won't work.
Can we obtain n from this array?
No.
The way I think about it is this. The line
int[][] arr = new int[a][b];
is essentially the same as
int[][] arr = new int[a][];
for (int i = 0; i < a; i++)
arr[i] = new int[b];
If a == 0, the for loop does nothing, so the value of b is irrelevant.
since every second level in this array is distinct, you will not be able to find out.
consider this:
int[][] a = new int[10][20];
a[0] = new int[5];
a[1] = new int[8];
for(int[] x : a) {
System.err.println(x.length);
}
and you will see that each X component is actually a pointer to another int[] object that can be set and mondified independently. by doing
int[][] a = new int[0][n];
you never actually create any of those pointers, and you don't create any of the Y components in there.

Implementing my own ArrayList using arrays

I have a project I have been assigned in java and I have to basically create my own class that mimics basic features of the ArrayList class.
I have to do it in the format shown below using these variables but I am stuck on one part. When the array fills up I want to make a new one with 10 extra spaces, then copy all the old array elements to the new one and use that from now on. How do I make my program automatically use this array from now on? Because it will continue to use the first array.
public MyArrayList()
{
array = new String[10];
arraySize = 10;
arrayElements = 0;
}
public void add (String string)
{
if (arrayElements < arraySize)
{
array[arrayElements] = string;
arrayElements++;
} else
{
arraySize += 10;
arrayElements++;
String[] array2 = new String[arraySize];
for (int i = 0; i < arrElements;i++)
{
array2[i] = array[i];
}
//missing code here I think?
array2[arrayElements] = string;
}
}
Assign array2 to the array reference. Something like,
//missing code here I think?
array2[arrayElements] = string;
array = array2;
Or, use Arrays.copyOf(int[], int) and something like
arraySize += 10;
arrayElements++;
array = Arrays.copyOf(array, arraySize); // <-- will pad with zeros.
MyArrayList uses array to hold its contents; in add you have created a new version of this in array2; just assign that to array.
You have multiple problems:
You create a new temporary array (array2) and copy existing values, but you don't update the array field to point to the new array.
You increment arrayElements too early.
Your code should be (pseudo-code):
add(newVal) {
if (array is full) {
newarray = new [array.size + extra]
copy values from array to newarray
array = newarray
}
add newVal to array and increment value count
}
See. You should only add new value in one place.
That is the DRY principle (Don't Repeat Yourself).
This can be a solution to increase the size of your array
String[] array2 = new String[array.length + 10];
System.arraycopy(array , 0, array2 , 0, array.length);
array = array2 ;

Generating Array with some specific values

I have to generate prime number. For this reason I have to initialize all array elements to -1. From c/c++, I came to know I have to initialize them by using a for loop. Please see the code below
public static void main(String[] args){
final int SIZE = 1000;
int[] intArray = new int[SIZE];
Arrays.fill(intArray, -1);
for(int i=0; i<SIZE; i++){
intArray[i] = -1;
}
for(int i = 0; i<SIZE; i++){
System.out.println(intArray[i]);
}
}
In java is there any better way to do this?
Well, Arrays.fill(intArray, -1); already fills your array, so there's no need for the redundant for loop following that statement.
You can also just remove your final int SIZE, and say int[] intArray = new int[1000];. When you need to get the length/size of the array, you can just say intArray.length.
You can only use Arrays.fill(int[] a, int val) method like this -
Arrays.fill(intArray, -1);
The Arrays.fill() populates the array - intArray with the specified value val. So you don't need to initialize the intArray using the for loop.
And one more thing, in c++ it is also possible to initialize array with some value like this, without using the for loop. See here

Adding integers to an int array

I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended

Array in Java, how to populate

Hi i'd like to populate array in Java. I'm trying to do it on easily way
int[] tab = null;
for(int i=0; i<5; i++)
{
tab[i]=i;
}
Why this constructions not working ?
error: null pointer exception
This is how you implement it
int[] tab = new int[5];
for(int i=0; i<tab.length; i++)
{
tab[i]=i;
}
Dynamic allocation means you should be using one of the Collection instances, such as a List. If you have some constraint (such as homework rules) that says you must use an array, then you have to do the following:
declare and instantiate the array to some arbitrary size: int[] intArray = new int[20];
during the addition of the elements, check if the index is equal to the length - 1: if(index == length - 1) , and if true,
create a temporary array of a size that is some multiple of the original array's size (usually 2x) int[] temp = new int[intArray.length*2];
copy the elements from the original array to the temp array
reassign the temp variable value to the original: intArray = temp;
after the loop, create a new array that is the correct length and copy all values from the original to the new one. (this is because the size will most certainly be wrong -- the length will be more than the number of elements).
In pseudo code, it looks like this:
int[] intArray = new int[20];
int index = 0;
loop:
if(index >= intArray.length - 1){
int[] temp = new int[intArray.length * 2];
copyAll: intArray->temp // use System.arrayCopy
intArray = temp;
}
intArray[index] = value;
index++;
endloop:
// resize because intArray will likely be too big
int[] temp = new int[index];
copyAll intArray -> temp;
intArray = temp;
As you can see, it's much, much nicer to use the Collection framework:
List<Integer> intList = new ArrayList<Integer>();
loop:
intList.add(value);
endloop
Here is how I would implement this array in the simplest way possible:
int[] tab = new int[]{0, 1, 2, 3, 4};
Your code doesn't work because you never create a new object to hold the elements of the array, it just creates space for a reference to that object. Before you can reference the object using
tab[i]
you must create a new object like this:
tab = new int[5];
So, if you really want to implement this variable in a for loop for whatever reason, here's how you should do it:
final int ARRAY_SIZE = 5;
int[] tab = new int[ARRAY_SIZE];
for(int i=0; i<ARRAY_SIZE; i++){
tab[i] = i;
}
Now, if you want to increase the number of elements in your array, you just need to change the ARRAY_SIZE variable.
You need to initialize your array before you use it:
int[] tab = new int`[5];
If you need something that is dynamicaly allocated use something like Vector or ArrayList:
For example:
ArrayList<Integer> list = new ArrayList<Integer>();
int elements_to_add = 5;
for(int i=0; i<elements_to_add; i++)
{
list.add(new Integer(i) );
}
Despite the fact that you declare this array and pass it null, you don't create any object here. You have only a reference to null. That's the reason of your error. What you have to do is initialize this array like int []myArray = new int[5];
Something like this should work :
int[] tab = new int[5];
for(int i=0; i<5; i++){
tab[i] = i;
}

Categories