Hi,
Can you tell why this class has somethig like this? was it already in any topic and i havent seen it? --- public static class Pair<X, Y>
can someone tell me what is...?
Dyskutowane
Komentarze (2)
- Popularne
- Najnowsze
- Najstarsze
Musisz się zalogować, aby dodać komentarz
Guadalupe Gagnon
5 października 2021, 20:53
Its called generics, though you don't need to know that to solve this task. They will touch upon it in later lessons.
I will give a quick explanation though:
In the class X an Y are just variables that can be any class (hence generic). You don't have to use X and Y in your code, you could create a generic class using any name for the generics, only governed by Java's naming rules. This code be exactly identical to the code in the task:
The generics are declared in angle brackets then referenced in code
When creating an object you declare what class that you want those generics to be and the X and Y for that object will be replaced with those classes. You have used them already: the List, Map, Set classes are all generic based:
new ArrayList<Integer>() - this will create a List for holding Integers
new HashSet<String>() - this will create a Set for holding Strings
new Pair<Integer, Integer>(0, 0) - This will create a pair for Integer Integer, with them being set to 0 and 0.
If I were to create a new Pair object using String Integer instead:
new Pair<String, Integer>("0", 0)
the class code for that particular object would be compiled to:
Where you can see that the X has been replaced in ALL cases by the class String, and the Y has been replaced in all cases with Integer. This is how you use generics. 0
Guadalupe Gagnon
5 października 2021, 21:00
Just remember that the important part is when you create a new object using a class with generics. You pass the classes you want to use in the angle brackets with the new object and all the Xs and Ys in the code will be replaced FOR THAT ONE OBJECT with those classes in the class code.
0