0

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.

3
  • you can't simply cast parent objects to child objects (unless your parent pointers were instantiated with child objects, which is not the case here - mixedData is still an array of Object, not Data) Commented Jul 29, 2020 at 0:57
  • 1
    You can test each entry in the objects array using instanceof. For example if (objects[i] instanceof String) {do something...}. And from your code, since objects is being received, you should not reinstantiate it with the line objects= new Object[MAX_LIST_SIZE];. Unless you want to work with two blank arrays Commented Jul 29, 2020 at 1:04
  • If you have to use instanceof, then you aren't using polymorphism. Commented Jul 29, 2020 at 6:27

2 Answers 2

1

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;
  }
Sign up to request clarification or add additional context in comments.

Comments

1
  1. Since both arrays are of same length, you have to decide how to handle an array element that doesn't contain a decimal number. For example, the interned String object "Nothing here at all" doesn't contain any numerical values, so once we process the string, it will return a null value.

  2. Shallow copy: since the field is a primitive type (double), use the = operator to assign its value to the array at the right index.

  3. You can change the code easily to implement the use of a Scanner to scan the String for numbers as required. Create a new scanner object and pass the string you're processing in the constructor.

/**
 * Output:
 * Single obj: 2.4
 * Single obj: 3.6
 * List obj: 3.2 6.8
 * Data obj: null
 * List obj: 1.2 7.9 4.5
 * List obj: 1.0 2.0 3.0
 * Single obj: 9.8
 *
 * @author martinfall
 */
public class TestData {

    public static void main(String[] args) {
        // Given
        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)};

        // Convert mixedData and assign the result to a Data array
        Data[] arr = convert(mixedData);

        // Print to console (Not required but helpful to see the output of each obj)
        for (Data datum : arr) {
            if (datum instanceof Single) {
                System.out.print("Single obj: ");
                System.out.println(((Single) datum).value); // Can encapsulate
            } else if (datum instanceof List) {
                System.out.print("List obj: ");
                for (double num : ((List) datum).arr) {
                    System.out.print(num + " ");
                }
                System.out.println();
            } else {
                // Since required that both arrays be equal size,
                // not sure how to handle an element of mixedData that doesn't
                // contain any decimal numbers
                System.out.println("Data obj: " + datum);
            }
        }
    }

    public static Data[] convert(Object[] objects) {
        // Find the length of objects and assign it to MAX_LIST_SIZE
        final int MAX_LIST_SIZE = objects.length;

        // Create a new array of Data objects using the length of objects
        Data[] arr = new Data[MAX_LIST_SIZE];

        // Loop throught the array and copy each element as required
        for (int i = 0; i < MAX_LIST_SIZE; i++) {
            if (objects[i] instanceof Single) {
                arr[i] = (Data) objects[i]; // Shallow copy
            } else if (objects[i] instanceof List) {
                arr[i] = (Data) objects[i];
            } else if (objects[i] instanceof String) {
                // Since both arrays have to be the same length, we have to add
                // the null value that is returned if a string doesn't contain
                // a numerical value
                arr[i] = processString((String) objects[i]);
            }
        }
        return arr;
    }

    public static Data processString(String str) {
        // Regular expression to match double values
        String regex = "^[-+]?\\d*(\\.\\d+)?$";
        // Counter variable to use to find out if list or single is returned
        int count = 0;
        // Create a blank Data variable
        Data d = null;
        // Split the String
        String[] split = str.split(" ");

        // Determine if Single or List
        for (String s : split) {
            if (s.matches(regex)) {
                count++;
            }
        }

        // If count is 1, return a Single
        if (count == 1) {
            for (String s : split) {
                if (s.matches(regex)) {
                    d = new Single(Double.parseDouble(s));
                }
            }
        } else if (count > 1) {
            // Create a new array as large as count
            double[] arr = new double[count];
            // Index of arr
            int arrIndex = 0;
            for (String s : split) {
                if (s.matches(regex)) {
                    arr[arrIndex] = Double.parseDouble(s);
                    arrIndex++;
                }
            }
            d = new List(arr);
        }
        return (Data) d;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.