Exercises

  • Exercise 1:
  • Define a generic class Point so that it is applicable whatever the type of its coordinates (int or double).




    Solution :


    class Point<T> {

      T x, y;

      Point(this.x, this.y);

    }

     

    void main() {

      var p1 = Point<int>(14);

      var p2 = Point<double>(1.24.5);

    }



  • Exercise 2:
  • Use a generic method that return the number of occurence of an element in a given list. Test it with 3 lists of type int , double and string.




    Solution :


    int occurence<T>(List<T> list, T element) {

      int res = 0;

      for (T e in list) {

        if (e == element) res++;

      }

      return res;

    }

     

    void main() {

      var li = <int>[14512454],

          ld = <double>[1.43.143.143.66.1],

          ls = <String>["flutter""dart""apps"];

      print(occurence(li, 4));

      print(occurence(ld, 3.14));

      print(occurence(ls, "apps"));

    }



    3
    2
    1