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:
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?
Java provides the instanceof operator to test if an object is of a certain type, or a subclass of that type. The program can then choose to cast or not cast that object accordingly. Object obj = Calendar. getInstance(); long time = 0; if(obj instanceof Calendar) { time = ((Calendar)obj).
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With