51

How can check if we can cast an object to another?

I have an object that it is an Arraylist of instances of an class that can be dynamically in 2 other class. How can I check that I can cast my object to each of them Arraylist class?

For example:

  • My classes are class1, class2 and class3.
  • My object is obj.

I want check it:

ArrayList<class1> ar1=new Arraylist<class1>(); ar1=(ArrayList<class1>)obj; 

How can I check if it can be true or false?

5
  • 10
    have you ever heard about 'instanceof'? and also "convert" is the correct spelling. Commented Jul 20, 2013 at 7:17
  • 1
    Please refer to stackoverflow.com/questions/7526817/use-of-instance-of-in-java Commented Jul 20, 2013 at 7:30
  • 5
    and also 'cast' is the correct term, not 'convert'. Commented Jul 20, 2013 at 8:26
  • Post linked by John Snow is a good place to start. But instanceof should be hardly needed when application is properly designed - please see <? extends T> construct - stackoverflow.com/questions/897935/… Commented Jul 20, 2013 at 8:35
  • possible duplicate of What is the 'instanceof' operator used for? Commented Jul 20, 2013 at 11:14

1 Answer 1

75

Something like this :-

import java.util.ArrayList; public class qu { public static void main(String args[]) { ArrayList<String> ar1=new ArrayList<String>(); ArrayList<Character> obj = new ArrayList<Character>(); if(obj instanceof java.util.ArrayList) System.out.println("My problem Solved"); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.