I have seen what is used for ArrayList<String> but I have no idea what it is. Who can explains without references to the wise reference orakl.
1 answer
Generics are used to write classes in which a part of the variables (or return values ββof the methods) does not have a predetermined type and allows the use of different types for internal variables. For example, in the case of List can create lists of numbers, strings, or any other classes. The type transferred to the <> triangle brackets becomes the array type that is used inside the List implementation, and the get and set methods of the List implementation start giving away this type defined by the programmer.
Thus, generics allow you to write generalized implementations of classes with previously unknown types of internal variables. It is very comfortable and cool, even though at first itβs not clear)
Example:
public class MyClass<T> { T foo; public T getFoo() { return foo; } public void setFoo(T foo) { this.foo = foo; } } Because in this class the type of the variable foo is not predefined, it can be of any type.
//ΡΠΈΠΏ ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ½ Π½Π°ΠΌΠΈ ΠΊΠ°ΠΊ Integer, Π·Π½Π°ΡΠΈΡ ΡΠΎΠ»ΡΠΊΠΎ Π΅Π³ΠΎ (ΠΈ Π΅Π³ΠΎ ΠΏΠΎΡΠΎΠΌΠΊΠΎΠ²) ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ ΠΏΡΠΈ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠΈ ΡΡΠΎΠ³ΠΎ ΡΠΊΠ·Π΅ΠΌΠΏΠ»ΡΡΠ° MyClass<Integer> integerFoo = new MyClass<>(); integerFoo.setFoo(5); //integerFoo.setFoo("5"); - ΠΎΡΠΈΠ±ΠΊΠ° ΠΊΠΎΠΌΠΏΠΈΠ»ΡΡΠΈΠΈ, Ρ.ΠΊ. String Π½Π΅ Integer //ΡΠΈΠΏ ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ½ Π½Π°ΠΌΠΈ ΠΊΠ°ΠΊ String, Π·Π½Π°ΡΠΈΡ ΡΠΎΠ»ΡΠΊΠΎ Π΅Π³ΠΎ (ΠΈ Π΅Π³ΠΎ ΠΏΠΎΡΠΎΠΌΠΊΠΎΠ²) ΠΌΠΎΠΆΠ½ΠΎ ΠΈΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΡ ΠΏΡΠΈ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠΈ ΡΡΠΎΠ³ΠΎ ΡΠΊΠ·Π΅ΠΌΠΏΠ»ΡΡΠ° MyClass<String> stringFoo = new MyClass<>(); stringFoo.setFoo("5"); //stringFoo.setFoo(5); - ΠΎΡΠΈΠ±ΠΊΠ° ΠΊΠΎΠΌΠΏΠΈΠ»ΡΡΠΈΠΈ, Ρ.ΠΊ. Integer Π½Π΅ String If there were no generics, then, for example, using lists would be a pain β when retrieving an object from it, you would have to manually cast the desired type each time (or, worse, create one list implementation for each data type for a list ):
//Π±Π΅Π· Π΄ΠΆΠ΅Π½Π΅ΡΠΈΠΊΠΎΠ² List listOfObjects = new ArrayList(); listOfObjects.add("string"); //ΡΡΠ΅Π±ΡΠ΅ΡΡΡ ΠΊΠ°ΡΡΠ°Π½ΡΡΡ ΡΡΠΊΠ°ΠΌΠΈ ΠΎΠ±ΡΠ΅ΠΊΡ ΠΊ ΡΡΡΠΎΠΊΠ΅ String stringFromObjectsList = (String) listOfObjects.get(0); //Ρ Π½ΠΈΠΌΠΈ List<String> listOfStrings = new ArrayList<>(); listOfStrings.add("string"); //ΠΠ ΡΡΠ΅Π±ΡΠ΅ΡΡΡ ΠΊΠ°ΡΡΠΎΠ²Π°ΡΡ ΡΡΠΊΠ°ΠΌΠΈ ΠΎΠ±ΡΠ΅ΠΊΡ ΠΊ ΡΡΡΠΎΠΊΠ΅ String stringFromStringList = listOfStrings.get(0); - Thank you, can you give an example? - ishidex2
- Straight out, just read a book about java everywhere they were used and the book itself was not explained - ishidex2
- @Duoxx, example added to the answer) - YuriySPb β¦
- ideone.com/cL7Hg6 - ishidex2
- Yes, a useful thing. - ishidex2
List<Integer> list = new ArrayList<>()butObject list = ArrayList<Integer>()- pavel