Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Logidata+ Deductive Databases With Complex Objects Lncs 701

Authors: Paolo Atzeni

1st Edition

354056974X, 978-3540569749

More Books

Students also viewed these Databases questions