Search code examples
javaarraysobjectpolymorphismhierarchy

Polymorphism: handling an array of objects java


In this program, I have to use the concept of polymorphism,

I have 1 abstract superclass named Data, and 2 subclasses named List and Single. Single accepts a double value(Constructor: public Single(value)). List accepts an array of doubles.( Constructor: List(double[] arr)), and in my main method, the following array,...

public static void main(String[] args) {

    Object[] mixedData = {
      new Single(2.4),
      "The data is 3.6",
      new List(new double[] {3.2,6.8}),
      "Nothing here at all",     
      new List(new double[] {1.2,7.9,4.5}),
      "Anda 1 anda 2 anda 3",
      new Single(9.8) };

I have to convert this Object[] array into Data[] array using a method:

  public static Data[] convert(Object[] objects){
    final int MAX_LIST_SIZE = 10;
  //***** YOUR CODE HERE *****
    objects= new Object[MAX_LIST_SIZE];
    Data[] data= new Data[MAX_LIST_SIZE];
    data = (Data[]) objects;
    for(int i=0; i<data.length; i++) {
        

    }
    return null; //Dummy statement - replace it
  }

In this method,

1)we have to make sure that both arrays are of same length.

2)Use shallow copy

3)If there is a String(if it contains a number), then change it to List object, containing all the numbers that can be found(as separate tokens) in the String. Use a Scanner to scan the String for numbers. Non-numbers should be ignored.

My Only doubt is that, in mixedData array, how can I find if it contains a String.

hope someone will answer.


Solution

  • I added some comments to your code to guide you through the solution.

    public static Data[] convert(Object[] objects){
        // If the objects array contains more than 10 elements what to do?
        // final int MAX_LIST_SIZE = 10;
        
        // Here you clear the content of the input objects, why?
        //objects= new Object[MAX_LIST_SIZE]; 
        
        // Set the length of data to the length of the input object array
        Data[] data= new Data[objects.length];
        
        // This cannot be done
        // data = (Data[]) objects; 
        
        for(int i=0; i<objects.length; i++) {
            if(objects[i] instanceof Single) {
                data[i] = (Single) objects[i];
            }else if(objects[i] instanceof List) {
                data[i] = (List) objects[i];
            }else if(objects[i] instanceof String) {
                String string = (String) objects[i];
                // Find all doubles with Scanner
                // Add the doubles to a List
                // Add the List to data[i]
            }
        }
        return data;
      }