Create a class named ArrayListIntroduce
that will serve as an introduction to ArrayList in Java. The class should have the following attributes and methods:
Attribute: numList
- an ArrayList of integers
Method: addNum(int num)
- takes an integer as a parameter and adds it to the numList
ArrayList.
Method: removeNum(int index)
- takes an integer index
as a parameter and removes the element at the specified index from the numList
ArrayList.
Method: findSum()
- calculates and returns the sum of all elements in the numList
ArrayList.
Method: printList()
- prints all the elements in the numList
ArrayList separated by a space.
You need to implement the ArrayListIntroduce
class and write a main method in a separate class called ArrayListExample
to test the functionality of the class. In the main method, perform the following operations:
Create an object of the ArrayListIntroduce
class called list
.
Add the following elements to the numList
ArrayList: 10, 20, 30, 40, 50.
Use the printList()
method to print the elements of the numList
ArrayList.
Use the removeNum()
method to remove the element at index 2.
Use the printList()
method again to print the updated elements of the numList
ArrayList.
Calculate the sum of the elements in the numList
ArrayList using the findSum()
method and print the result.
Your implementation in the ArrayListIntroduce
class should pass the given test case. Provide the implementation of the ArrayListIntroduce
class and the ArrayListExample
class as your answer.
public class ArrayListIntroduce {
private ArrayList<Integer> numList;
public ArrayListIntroduce() {
numList = new ArrayList<Integer>();
}
public void addNum(int num) {
numList.add(num);
}
public void removeNum(int index) {
numList.remove(index);
}
public int findSum() {
int sum = 0;
for (int num : numList) {
sum += num;
}
return sum;
}
public void printList() {
for (int num : numList) {
System.out.print(num + " ");
}
System.out.println();
}
}
public class ArrayListExample {
public static void main(String[] args) {
ArrayListIntroduce list = new ArrayListIntroduce();
list.addNum(10);
list.addNum(20);
list.addNum(30);
list.addNum(40);
list.addNum(50);
list.printList();
list.removeNum(2);
list.printList();
int sum = list.findSum();
System.out.println("Sum: " + sum);
}
}
In the given example, an ArrayListIntroduce object list
is created in the ArrayListExample class and various operations are performed on it. The addNum()
method is used to add elements to the numList
ArrayList, while the printList()
method is used to display the elements. The removeNum()
method is used to remove an element at the specified index. Finally, the findSum()
method calculates the sum of all elements in the numList
ArrayList.