1

I've been practicing with generic class representations to understand how they are working, and I have a theoretical question.

My generic class looks like:

public class CustomCollector<T> {

  private T t;
  //getter, setter
}

My representations are the following:

CustomCollector<ArrayList<Integer>> customCollectorA = new CustomCollector<>()
customCollectorA.setT(Arrays.asList(1, 3, 4)); 
//IntelliJ says Arrays.asList()gives back a List, 
//but an ArrayList is needed
//but Arrays.asList() gives back a List, so the types are incompatible

CustomCollector customCollectorB = new CustomCollector<ArrayList<Integer>>();
customCollectorB.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it

CustomCollector customCollectorC = new CustomCollector<List<Integer>>();
customCollectorC.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it    

CustomCollector<List<Integer>> customCollectorD = new CustomCollector<>();
customCollectorD.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it

CustomCollector<ArrayList<Integer>> customCollectorE = new CustomCollector();
customCollectorE.setT(Arrays.asList(1, 3, 4));
//IntelliJ says it's an unchecked assignment, if I add <>, then
//the error message disappears

I think if I want to understand what is happening here - unless if it's an IntelliJ error - I have to understand again what is happening when I create a new instance of an object. So the topic itself seems to be very easy, but I am struggling to reconcile my existent knowledge with the IntelliJ results of the representations.

My questions are the following:

  • Could you write me what is exactly happening when I am creating these objects?
  • Is there any convention how I should use these generic representations? For example, when to use the representation used in customCollectorC and when to use the one in customCollectorD?

Thank you in advance.

lyancsie
  • 658
  • 7
  • 18

0 Answers0