What does (angle brackets) mean in Java?

后端 未结 6 1546
轮回少年
轮回少年 2020-11-22 05:12

I am currently studying Java and have recently been stumped by angle brackets(<>). What exactly do they mean?

public class Pool{
    public inter         


        
6条回答
  •  花落未央
    2020-11-22 05:54

    Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects

    ArrayList employees = new ArrayList();
    ArrayList companies = new ArrayList();
    

    You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.

提交回复
热议问题