Results 1 to 2 of 2
Thread: Why is there (Integer) casting?
- 11-15-2010, 10:28 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 9
- Rep Power
- 0
Why is there (Integer) casting?
Friends,
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?
Why is there (Integer) casting in the above code?Java Code:sum += ((Integer)ia[i]).intValue();
Thanks a lot.
- 11-15-2010, 10:43 AM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
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:
you useJava Code:ArrayList list;
This way, the List will only accept Integer objects, and also return Integers (no need to cast).Java Code:ArrayList<Integer> list;
Ever seen a dog chase its tail? Now that's an infinite loop.
Similar Threads
-
convert unsigned integer to signed integer in java?
By diskhub in forum New To JavaReplies: 6Last Post: 05-17-2010, 12:50 AM -
Casting
By zzpprk in forum Advanced JavaReplies: 13Last Post: 08-13-2009, 07:59 PM -
What does casting mean?
By sev51 in forum New To JavaReplies: 3Last Post: 01-27-2009, 04:31 PM -
casting help
By soc86 in forum New To JavaReplies: 4Last Post: 01-13-2009, 11:07 PM -
Casting
By leebee in forum New To JavaReplies: 5Last Post: 08-10-2007, 12:24 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks