1

How can I know the instance of java.util.Arrays$ArrayList. I've tried this code snippet but it does not work at all :

if (myList instanceof Arrays) {
    //Do something here.
}

I have compared the object classtype with ArrayList and I had the same issue. But while I was inspecting the object, the classType was a :

class java.util.Arrays$ArrayList

The conditional statement below was the only solution I found:

else if (myList.getClass().toString().equals("class java.util.Arrays$ArrayList")) {
    //do something here
}

but I think that controlling the object type by using instanceof would be a great solution.

My question is : what is the classType of java.util.Arrays$ArrayList, so I can use instanceof for my control.

Thanks in advance,

Omar.

fabian
  • 80,457
  • 12
  • 86
  • 114
EKO
  • 47
  • 1
  • 6

3 Answers3

3

in case the list comes from Arrays#asList, the returned ArrayList is NOT java.util.ArrayList, therefore a comparison to this class will always fail.

The question is, why do you need to know that it is exactly this implementation ? Maybe it is enough to check for java.util.List ?

In general it is questionable why you need the instanceof operator at all, often there are other design solutions better.

Emerson Cod
  • 1,990
  • 3
  • 21
  • 39
  • It's because of the nature of the project I'm working on. I receive a Arrays.asList() list and I couldn't change it since I'm not working on this part of the project. At last, the solution was to ask the person who works on creating the list to send me a java.util.ArrayList and it worked! Thanks for the help anyway! – EKO Oct 26 '15 at 21:44
  • you can also simply wrap the retrieved list in a new list and then you can work with that further – Emerson Cod Oct 27 '15 at 10:54
2

java.util.Arrays$ArrayList is a private inner class of Arrays, returned by the Arrays.asList method.

Since it's a private class there is no way to get access to the class in a way that it can be used with the instanceof operator. You can do this check using reflection however:

Class<?> clazz = Class.forName("java.util.Arrays$ArrayList");
// ...
clazz.isAssignableFrom(myList)

But I do not recommend doing that. It's a good practice to program against an interface. In this case the List interface defines the behavior of the object. The actual class of the object shouldn't matter.

Community
  • 1
  • 1
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Thanks for your help I didn't know that in the case of **ClassA$ClassB** ClassB is a private inner class of ClassA. – EKO Oct 26 '15 at 21:49
-1

Why are you using Arrays ? You must use ArrayList like in this code

if (myList instanceof ArrayList) {
    //Do something here.
}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77