Implement a Java class ArrayListOperations
which contains the following methods:
sum(ArrayList<Integer> nums): int
- This method takes in an ArrayList of Integers and returns the sum of all the elements in the ArrayList.
isUnique(ArrayList<Integer> nums): boolean
- This method takes in an ArrayList of Integers and returns whether or not all the elements in the ArrayList are unique (i.e., there are no duplicate elements).
removeDuplicates(ArrayList<Integer> nums): ArrayList<Integer>
- This method takes in an ArrayList of Integers and removes any duplicate elements, returning the modified ArrayList.
getUnion(ArrayList<Integer> nums1, ArrayList<Integer> nums2): ArrayList<Integer>
- This method takes in two ArrayLists of Integers and returns a new ArrayList that contains all distinct elements from both lists (no duplicate elements).
Your task is to implement the ArrayListOperations
class along with the above methods.
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
ArrayList<Integer> duplicates = new ArrayList<>(Arrays.asList(1, 2, 2, 3, 4, 5));
ArrayListOperations op = new ArrayListOperations();
// Testing sum() method
int sum = op.sum(numbers);
System.out.println(sum); // Output: 15
// Testing isUnique() method
boolean unique = op.isUnique(numbers);
System.out.println(unique); // Output: true
boolean containsDuplicates = op.isUnique(duplicates);
System.out.println(containsDuplicates); // Output: false
// Testing removeDuplicates() method
ArrayList<Integer> noDuplicates = op.removeDuplicates(duplicates);
System.out.println(noDuplicates); // Output: [1, 2, 3, 4, 5]
// Testing getUnion() method
ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(3, 4, 5));
ArrayList<Integer> union = op.getUnion(list1, list2);
System.out.println(union); // Output: [1, 2, 3, 4, 5]
ArrayListOperations
class.ArrayList
.The ArrayListOperations
class defines several methods for performing operations on ArrayLists. The sum
method calculates the sum of all elements in the ArrayList by iterating over each element and accumulating the sum. The isUnique
method checks for duplicate elements by iterating over each element and using a HashSet to keep track of unique elements. If the HashSet already contains an element, it means there's a duplicate. The removeDuplicates
method removes any duplicate elements from the ArrayList by iterating over each element and using a HashSet to keep track of unique elements. The resulting ArrayList only contains unique elements. The getUnion
method combines two ArrayLists by creating a HashSet and adding all elements from the first ArrayList, then adding all elements from the second ArrayList. The resulting HashSet only contains distinct elements which are then converted back to an ArrayList.