Question: Using my code import java.util. * ; / / Generic class to store data of any type class GenericArrayStorage { private T [ ] array;

Using my code import java.util.*;
// Generic class to store data of any type
class GenericArrayStorage {
private T[] array;
private int capacity;
private int size;
// Constructor
public GenericArrayStorage(int capacity){
this.capacity = capacity;
this.size =0;
this.array =(T[]) new Object[capacity];
}
// Method to add data to the array
public void add(T data){
if (size < capacity){
array[size++]= data;
} else {
System.out.println("Array is full. Cannot add more elements.");
}
}
// Method to get data from the array at index
public T get(int index){
if (index < size && index >=0){
return array[index];
} else {
throw new ArrayIndexOutOfBoundsException("Index out of bounds.");
}
}
// Method to sort the array based on a comparator
public void sort(Comparator comparator){
Arrays.sort(array,0, size, comparator);
}
// Method to display the array
public void display(){
for (int i =0; i < size; i++){
System.out.println(array[i]);
}
}
}
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
// Creating a generic array storage for Strings
GenericArrayStorage storage = new GenericArrayStorage<>(5);
// Reading data from the user and storing it
for (int i =0; i <5; i++){
System.out.print("Enter data: ");
String data = scanner.nextLine();
storage.add(data);
}
// Displaying unsorted data
System.out.println("Unsorted Data:");
storage.display();
// Sorting based on user input (String length in this example)
System.out.println("Sorting based on length:");
storage.sort(Comparator.comparingInt(String::length));
// Displaying sorted data
storage.display();
scanner.close();
}
}
Add Efficiently search the data based on the field specified by the user (using a comparator). without changing the code

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!