Generic là gì?
Generic có nghĩa là ta viết các phương thức và lớp để tái sử dụng cho các đối tượng thuộc các kiểu dữ liệu khác nhau.
Ví dụ:
Viết một chương trình quản lý danh sách học sinh và giáo viên, sử dụng List để lưu lại danh sách của học sinh và giáo viên.
List<Student> students = new ArrayList<Student>(); List<Teacher> teachers = new ArrayList<Teacher>();
List được cài đặt theo cách generic nên ta có thể tái sử dụng lại được các kiểu dữ liệu khác nhau (lúc thì chứa sinh viên , lúc thì chứa giáo viên). Sinh viên và giáo viên là 2 kiểu dữ liệu khác nhau. Do vậy tuỳ vào ngữ cảnh ta truyền vào cho List thì nó có là danh sách sinh viên (List <Student >) hay nó có thể là danh sách giáo viên (List < Teacher >).
Kí hiệu <T>
class Person<T> { private T id; public Person(T id){ this.id = id; } public T getId(){ return id; } }
T đại diện cho 1 Type ⇒ Khi báo biến và khởi tạo object, bạn phải thay thế
T
bằng 1 type cụ thể (String, Integer, Bigdecimal …)Bài tập
Write a Java program to create a generic method that takes a list of any type and a target element. It returns the index of the first occurrence of the target element in the list. Return -1 if the target element cannot be found.
Lý thuyết Generic Functions:
public <T> List<T> fromArrayToList(T[] a) { return Arrays.stream(a).collect(Collectors.toList()); } public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) { return Arrays.stream(a) .map(mapperFunction) .collect(Collectors.toList()); }
The <T> in the method signature implies that the method will be dealing with generic type T.
This is needed even if the method is returning void.
Lý thuyết Generic Class:
// Java program to show working of user defined // Generic classes // We use < > to specify Parameter type // Syntax: class class_name<type-param-list> {...} class Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; } } // Driver class to test above class Main { public static void main(String[] args) { // instance of Integer type Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test<String> sObj = new Test<String>("GeeksForGeeks"); System.out.println(sObj.getObject()); } } // Output: 15 //GeeksForGeeks
Giải bài tập
// FindElement.java // FindElement Class import java.util.List; public class FindElement { public static < T > int findIndexOfElement(List < T > list, T target) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(target)) { return i; } } return -1; } public static void main(String[] args) { List < Integer > numbers = List.of(1, 2, 3, 4, 5); List < String > colors = List.of("Red", "Green", "Blue", "Orange", "White"); System.out.println("Original list elements:"); System.out.println("Nums: " + numbers); System.out.println("Colors: " + colors); int index1 = findIndexOfElement(numbers, 3); System.out.println("\nIndex of 3 in numbers: " + index1); // Output: 2 int index2 = findIndexOfElement(numbers, 6); System.out.println("Index of 6 in numbers: " + index2); // Output: -1 int index3 = findIndexOfElement(colors, "Green"); System.out.println("Index of \"Green\" in colors: " + index3); // Output: 1 int index4 = findIndexOfElement(colors, "Black"); System.out.println("Index of \"Black\" in colors: " + index4); // Output: -1 } }
Write a Java program to create a generic method that takes a list of any type and returns it as a new list with the elements in reverse order.
// ReverserList.java // ReverserList Class import java.util.ArrayList; import java.util.List; public class ReverserList { public static < T > List < T > reverseList(List < T > originalList) { List < T > reversedList = new ArrayList < > (); for (int i = originalList.size() - 1; i >= 0; i--) { reversedList.add(originalList.get(i)); } return reversedList; } public static void main(String[] args) { List < Integer > numbers = List.of(1, 2, 3, 4, 5, 6); List < String > colors = List.of("Red", "Green", "Orange"); List < Integer > reversedNumbers = reverseList(numbers); System.out.println("Original list of numbers: " + numbers); System.out.println("Reversed numbers: " + reversedNumbers); // Output: [6, 5, 4, 3, 2, 1] List < String > reversedWords = reverseList(colors); System.out.println("\nOriginal list of colors: " + colors); System.out.println("Reversed colors: " + reversedWords); // Output: [Orange, Green, Red] } }