Results 1 to 2 of 2
  1. #1
    hitesh_public is offline Member
    Join Date
    Aug 2010
    Rep Power

    Default Why is there (Integer) casting?


    Java Code:
    // Obtaining an array from an array list
    import java.util.*;
    class ArrayListToArray {
      public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add(new Integer(1));
        al.add(new Integer(2));
        al.add(new Integer(5));
        al.add(new Integer(9));
        System.out.println("The contents of the array list are" + al);
        Object ia[] = al.toArray();
        int sum = 0;
        for(int i = 0; i < ia.length; i++) 
          sum += ((Integer)ia[i]).intValue();
        System.out.println("The sum is" + sum);

    What does this statement does?

    Java Code:
    sum += ((Integer)ia[i]).intValue();
    Why is there (Integer) casting in the above code?

    Thanks a lot.

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Ljubljana, Slovenia
    Rep Power


    Because non-generic Lists return objects. As you see, you declared the array to hold Object-type elements, so you need to cast them to Integer before you can use a mathematical operation on them. This is solved by using generics, instead of:
    Java Code:
    ArrayList list;
    you use
    Java Code:
    ArrayList<Integer> list;
    This way, the List will only accept Integer objects, and also return Integers (no need to cast).
    Ever seen a dog chase its tail? Now that's an infinite loop.

Similar Threads

  1. convert unsigned integer to signed integer in java?
    By diskhub in forum New To Java
    Replies: 6
    Last Post: 05-17-2010, 12:50 AM
  2. Casting
    By zzpprk in forum Advanced Java
    Replies: 13
    Last Post: 08-13-2009, 07:59 PM
  3. What does casting mean?
    By sev51 in forum New To Java
    Replies: 3
    Last Post: 01-27-2009, 04:31 PM
  4. casting help
    By soc86 in forum New To Java
    Replies: 4
    Last Post: 01-13-2009, 11:07 PM
  5. Casting
    By leebee in forum New To Java
    Replies: 5
    Last Post: 08-10-2007, 12:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts