Given the following code how should the toString methods in

Given the following code, how should the toString methods in the classes H2ClassA and H2ClassB be written to give the indicated output and take advantage of the natural toString method in H2ClassB?

1 import java.util.ArrayList;

2

3 public class H2ClassA {

4    ArrayList list = new ArrayList ();

5

6    public static void main (String args []) {

7      H2ClassA y = new H2ClassA ();

8      int [] v = {4, 3, 7, 5, 99, 3};

9      for (int m: v)

10       y.list.add (new H2ClassB (m));

11     System.out.println (y);

12   } // end main

13

14 } // end class H2ClassA

15

16 class H2ClassB {

17   int x;

18   H2ClassB (int a) { x = a;}

19 } // end H2ClassB

OUTPUT: 4 3 7 5 99 3

Solution

HI Friend, I have added required functions.It is working correctly.

Please let me know in case of any issue.

import java.util.ArrayList;

public class H2ClassA {

   ArrayList<H2ClassB> list = new ArrayList<H2ClassB> ();

   public static void main (String args []) {

       H2ClassA y = new H2ClassA ();

       int [] v = {4, 3, 7, 5, 99, 3};

       for (int m: v)

           y.list.add (new H2ClassB (m));

       System.out.println (y);

   } // end main

  

   @Override

   public String toString() {

       String res = \"\";

       for(H2ClassB classB : list){

           res = res + classB+\" \";

       }

      

       return res;

   }

} // end class H2ClassA

class H2ClassB {

   int x;

   H2ClassB (int a) { x = a;}

  

   @Override

   public String toString() {

       return Integer.toString(x);

   }

} // end H2ClassB

// OUTPUT: 4 3 7 5 99 3

Given the following code, how should the toString methods in the classes H2ClassA and H2ClassB be written to give the indicated output and take advantage of the
Given the following code, how should the toString methods in the classes H2ClassA and H2ClassB be written to give the indicated output and take advantage of the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site