Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 608
user2601734 Avatar asked Jul 20 '13 07:07

user2601734


People also ask

How do you check if an object can be cast to another object in Java?

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).

How do you check if an object is an instance of another object?

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.

What is the purpose of casting an object to another type?

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.


1 Answers

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");     } } 
like image 128
John Snow Avatar answered Oct 16 '22 13:10

John Snow