0

If I have two empty arraylists, how can I check if they accept the same class of object.

The function would look something like,

    public boolean haveSameType(ArrayList array1, ArrayList array2){ ... }'

In the general case, I want to be able to compare the generics of any two objects in a class.

Edit:

In my specific case I have an abstract class

    public abstract class Dog<E extends Cat> { ... }

and I am trying to compare 2 objects which I know are of the class Dog (or a subclass obviously). However I cannot say

    Dog aDog //gives a warning because Dog should be parameterized

So what is the correct way to create this variable?

multitaskPro
  • 569
  • 4
  • 14
  • 1
    This is not a runtime check you should be doing. It's a compile time check. Let generics do the work for you. Do not use raw types. – Savior Apr 21 '16 at 23:23
  • 1
    You can't do it because of [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). – shmosel Apr 21 '16 at 23:23
  • @Pillar Thanks for the help, but I realize my question was slightly mistaken. I have an updated version now. – multitaskPro Apr 21 '16 at 23:36
  • Do not use raw types still stands. (See your warning.) – Savior Apr 21 '16 at 23:39
  • @Pillar I did a little bit of research and in eclipse using Dog> aDog doesn't throw an error in eclipse. So what I am taking away from this is that I can create an object without knowing its generic, but I can't access the generic of that object. Is that correct? – multitaskPro Apr 21 '16 at 23:43
  • 1
    This is complicated subject. There is no _generic of that object_. An object is a runtime concept and Java's runtime has no (almost) knowledge of generics. So, no, at runtime there'd be no way to find out. You can look at the objects inside the list itself (if it's not empty). – Savior Apr 21 '16 at 23:46
  • @Pillar alright thanks for all the help :) I'll see if I can find some more info and if not work an a workaround or something else entirely. – multitaskPro Apr 21 '16 at 23:49
  • If you haven't seen this yet, read http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – Savior Apr 21 '16 at 23:49

0 Answers0