Exercises
- Exercise 1:
- Exercise 2:
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>(1, 4);
var p2 = Point<double>(1.2, 4.5);
}
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>[1, 4, 5, 1, 2, 4, 5, 4],
ld = <double>[1.4, 3.14, 3.14, 3.6, 6.1],
ls = <String>["flutter", "dart", "apps"];
print(occurence(li, 4));
print(occurence(ld, 3.14));
print(occurence(ls, "apps"));
}
2
1