Implementing my own ArrayList using arrays - java

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 ;

Related

Array or ArrayList?

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

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

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

Creating and Using arrays

I am new to the concept of arrays in java, and as part of an assignment, I am required to create a 10 row by 3 column integer array and populate it with a for loop. I have the following.
public class arrays{
int arr[][][] = new int [10][10][10];
for(int i=0;i<arr.length;++i)
{
for(int j=0;j<arr[i].length;++j)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
am I on the right track?
You are actually declaring a 3-dimensional array.
You should instead be declaring int[][] arr = new int[10][3];.
You can then assign values as follows: arr[i][j] = 42;
Note also that when instantiated, the initial values in the array are 0.
The way of creating array in java is simple and I see you know that but for your problem applicable array might be different. Try that one
int arr[][] = new int [10][3];
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
arr[i][j] = your_integer_value;
}
}

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