Monday, July 18, 2016

How to know the data type of the elements from the list of collection objects in java

To know the data types from the list of collection objects in java is by using the below code


public class CheckDataTypes{

      pubic static void main(String[] args){
   
   List list = new ArrayList();
list.add(10);
list.add("hello");
list.add('a');
list.add(34.4);
list.add(22.3f);
for(Object obj:list){
if(obj.getClass().equals(String.class)){
System.out.println(" String type");
}else if(obj.getClass().equals(Integer.class)){
System.out.println("Integer type");
}else if(obj.getClass().equals(Float.class)){
System.out.println("Float type ");
}else if(obj.getClass().equals(Double.class)){
System.out.println("Double type ");
}else if(obj.getClass().equals(Character.class)){
System.out.println("Char Type");
}
}
      }//Main method closed

}// class ended



One more way is : 


public class DataType {
   public static void main(String args[]){
     
  List list = new ArrayList();
list.add(10);
list.add("hello");
list.add('a');
list.add(34.4);
list.add(22.3f);
for(Object obj:list){
if(obj instanceof String){
System.out.println(" String type");
}else if(obj instanceof Integer){
System.out.println("Integer type");
}else if(obj instanceof  Float){
System.out.println("Float type ");
}else if(obj instanceof  Double){
System.out.println("Double type ");
}else if(obj instanceof Character){
System.out.println("Char Type");
}
    }//for each loop closed
   }//main method closed
}//Class is closed

No comments:

Post a Comment