If an Arraylist contains multiple Class values then how will you separate that value and Store to a specific Data type of ArrayList.
In an interview it's has been asked the question of Arraylist as if you have an ArrayList and the ArrayList type is an object and it contains an integer value, double value, string value.
ArrayList contains Object |
How will you to separate the Arraylist to a specific class like integer value, double value, string value and store it to a specific Arraylist this question have has been asked in an interview round.
So here we came up with the solution of Arraylist that if Arraylist contains multiple values of different Class then you can separate an Arraylist by using instanceof operator in Java.
Using an instanceof operator it is very easy to separate to a specific Class or Data type.
import java.util.ArrayList; import java.util.List; public class Arraylist_DataType { public static void main(String[] args) { List<Integer> int_arraylist = new ArrayList<Integer>(); List<Double> Double_arraylist = new ArrayList<Double>(); List<String> string_arraylist = new ArrayList<String>(); List<Object> al = new ArrayList<Object>(); al.add("Apple"); al.add("Banana"); al.add(73.9); al.add("Carrot"); al.add(100); al.add(12.66); al.add("Elephant"); al.add(455); al.add("Fish"); al.add(233); al.add(30); al.add("Grapes"); al.add(34.55); for (int i = 0; i < al.size(); i++) { if (al.get(i) instanceof Integer) { int_arraylist.add(Integer.parseInt(al.get(i).toString())); } if (al.get(i) instanceof Double) { Double_arraylist.add(Double.parseDouble(al.get(i).toString())); } if (al.get(i) instanceof String) { string_arraylist.add(al.get(i).toString()); } } System.out.println("Ingeter--> " + int_arraylist); System.out.println("Double--> " + Double_arraylist); System.out.println("String--> " + string_arraylist); }
ArrayList contains Object |
Important:
What happened if an Arraylist contains primitive data types then you cannot use instanceof to primitive data type then in that scenario instanceof operator not work on primitive data type then you have to use isInstance that instance of an operator.
int number=20; System.out.println(Integer.class.isInstance(a)); //true }