Question

In Java: Create an addBefore and add method to the class IntArrayList. The method addBefore adds...

In Java: Create an addBefore and add method to the class IntArrayList. The method addBefore adds an element to the beginning of an array, at index 0, causing all existing elements to move forward (their indexes increased by 1). The method add creates an element at the end of the array. There are several ways to accomplish this task. Perhaps the easiest: double the array when you hit the beginning or end, copying it to the beginning or end dependent on if you're in the add or addBefore method.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Pls provide +ve ratings, Thanks

//IntArrayList.java file

class IntArrayList

{

//declare array of int array

private int []array;

//declare a variable to hold current size of array

private int currentSize;

private int capacity;

//declare constructor without parameter

public IntArrayList()

{

//declare the default capacity 5

array=new int[5];

currentSize=0;

capacity=5;

}

//double the size when default capacity is less to accomadate the array elements

public void doubleSize()

{

int []Temparray=new int[2*capacity];

//update new capacity

capacity=2*capacity;

//copy all the elements from IntArray to Temp array

for(int i = 0; i < currentSize; i++)

{

Temparray[i]=array[i];

}

//now assign the Temparray to IntArray

array=Temparray;

}

//addBefore method, add the element at the beginning of the array ,ie at the index 0

public void addBefore(int val)

{

//check if capacity of the array can accomodate the new element

if((currentSize+1) >= capacity )

{

//double the array size

doubleSize();

}

if(currentSize == 0) //IntArray is empty

{

array[0]=val;

++currentSize;

return ;

}

//push elements from 0 to the right , ie element at index 0 is pushed to index 1 , element at index 1 pushed down to index 2 and so on

for(int i =currentSize; i>0; i-- )

{

array[i]=array[i-1];

//System.out.println(""+array[i]);

}

//now assign the value to index 0

array[0]=val;

++currentSize;

}

//add method,adds element at the end of the array

public void add(int val)

{

if((currentSize+1) >= capacity)

{

doubleSize();

}

array[currentSize++]=val;

}

//helper method to display array elements

public void print()

{

System.out.println("Array elemensts are: ");

for(int i = 0; i < currentSize; i++)

{

System.out.println(""+array[i]);

}

}

}

==============================================================

//Main.java file

class Main {

public static void main(String[] args) {

//System.out.println("Hello world!");

//declare object of IntArrayList

IntArrayList intList = new IntArrayList();

// add elemenst using addBefore method

intList.addBefore(6);

intList.addBefore(5);

intList.addBefore(4);

intList.addBefore(3);

intList.addBefore(2);

intList.addBefore(1);

//print list

intList.print();

//add elements at the end of array

intList.add(7);

intList.add(8);

intList.add(9);

intList.add(10);

intList.add(11);

//print list

intList.print();

}

}

==========================

//output

Array elemensts are:
1
2
3
4
5
6
Array elemensts are:
1
2
3
4
5
6
7
8
9
10
11

Add a comment
Know the answer?
Add Answer to:
In Java: Create an addBefore and add method to the class IntArrayList. The method addBefore adds...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Improve the code below by creating an addBefore method. Instead of adding an element to the...

    Improve the code below by creating an addBefore method. Instead of adding an element to the end, addBefore adds it to the beginning, at position 0, causing all existing elements to move forward (their position increased by 1). However, like add, your addBefore method must also guarantee that only O(?) time is needed to perform n addBefores and adds. To accomplish this, as with add, most calls to addBefore must execute very quickly, in O(1) constant time, meaning that you...

  • JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

    JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class. Print out the results after testing each of the methods in both of the classes and solving a simple problem with them. Task 1 – ArrayList Class Create an ArrayList class. This is a class that uses an internal array, but manipulates the array so that the array can be dynamically changed. This class should contain a default and overloaded constructor, where the default...

  • Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int...

    Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int virtualArrayLength; // the number of elements in the dynamic array // Throws an IndexOutOfBoundsException if i is not a valid index // for adding to the dynamic array, otherwise inserts s at index i. // Elements can be added from index 0 to this.size(). public void add(int i, String s) { // If there is no room for s in data, create a new...

  • Java Program Create a class to store an array of with enough space to store 10 integer values. Us...

    Java Program Create a class to store an array of with enough space to store 10 integer values. Using the principle of recursion, implement the following: *getSize : returns the size of the array. *get (i): returns the i-th element of the array. If the element does not exist, it throws a "NoSuchElementException” which is a subclass of Java class RunTimeException. *add (val): inserts value as the last element of the array. If necessary, double the size of the current...

  • in java eclipse, Create a program “FibonacciFifteen.java” and a method called “double[] getFibonacci()” that creates an...

    in java eclipse, Create a program “FibonacciFifteen.java” and a method called “double[] getFibonacci()” that creates an array with a length of 15 that contains the first 15 numbers in the Fibonacci sequence and returns it. Set the first element to 0 and the second element to 1, then use a for loop to fill out the rest of the array by adding the prior two elements.

  • java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait)...

    java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait) where Comparator is an interface in java.util. Database: a class that limits the types it can store to DatabaseTypes. The database will store the data in nodes, just like a linked list. The database will also let the user create an index for the database. An index is a sorted array (or in our case, a sorted ArrayList) of the data so that searches...

  • You must create a Java class named TenArrayMethods in a file named TenArrayMethods.java. This class must...

    You must create a Java class named TenArrayMethods in a file named TenArrayMethods.java. This class must include all the following described methods. Each of these methods should be public and static.Write a method named getFirst, that takes an Array of int as an argument and returns the value of the first element of the array. NO array lists. Write a method named getLast, that takes an Array of int as an argument and returns the value of the last element...

  • Question 1[JAVA] Add a method in the Main class named getLines() that takes a filename as...

    Question 1[JAVA] Add a method in the Main class named getLines() that takes a filename as a String and returns each line in the file in an array. Have each element of the array be a String. Do not include the newline at the end of each line. Use a BufferedReader object to read the file contents. Note, the contents of input.txt will be different (including the number of lines) for each test case. Example: getLines( "input.txt" ) returns (an...

  • write in java 1. Assume the availability of a method  named  makeLine that can be passed a non-negative...

    write in java 1. Assume the availability of a method  named  makeLine that can be passed a non-negative integer  n and a character  c and return a String consisting of n identical characters that are all equal to c. Write a method  named  printTriangle that receives two integer  parameters  n and k. If n is negative the method does nothing. If n happens to be an even number, itsvalue is raised to the next odd number (e.g. 4-->5). Then, when k has the value zero, the method prints...

  • JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT