Results 1 to 3 of 3
  1. #1
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Question Casting int[][] to int[]

    The following piece of code gives me compiler error as expected "Cannot cast from int[][] to int[]"
    Java Code:
    int[][] a = {{1,2,}, {3,4}};
    int[] b = (int[]) a;
    But why doesn't the same compiler fail for the below code?
    Java Code:
    int[][] a = {{1,2,}, {3,4}};
    Object o1 = a;
    int[] b = (int[]) o1;
    Instead it gives runtime exception (java.lang.ClassCastException)

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default

    Quote Originally Posted by subith86 View Post
    The following piece of code gives me compiler error as expected "Cannot cast from int[][] to int[]"
    Java Code:
    int[][] a = {{1,2,}, {3,4}};
    int[] b = (int[]) a;
    But why doesn't the same compiler fail for the below code?
    Java Code:
    int[][] a = {{1,2,}, {3,4}};
    Object o1 = a;
    int[] b = (int[]) o1;
    Instead it gives runtime exception (java.lang.ClassCastException)
    The compiler is a bit short-sighted: an (up)cast is always allowed (a cast to type Object) and a down cast always is done and checked during runtime. The compiler is just too stupid to realize that the object o1 is identical to the object a (which is an int[][] and can't be cast to an int[]).

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    10

    Default

    What you're trying to do also doesn't make much sense. How exactely would you turn a 2D array into a 1D array? Unless what you're trying to do is assign one line of a 2D array to a variable. In that case, that can be achieved like this:
    Java Code:
    int[][] a = {{1,2},{3,4}};
    int[] b = a[0];
    Ever seen a dog chase its tail? Now that's an infinite loop.

Similar Threads

  1. Casting
    By zzpprk in forum Advanced Java
    Replies: 13
    Last Post: 08-13-2009, 08:59 PM
  2. forced casting
    By hen1610 in forum New To Java
    Replies: 1
    Last Post: 03-06-2009, 06:49 PM
  3. What does casting mean?
    By sev51 in forum New To Java
    Replies: 3
    Last Post: 01-27-2009, 05:31 PM
  4. casting help
    By soc86 in forum New To Java
    Replies: 4
    Last Post: 01-14-2009, 12:07 AM
  5. Casting
    By leebee in forum New To Java
    Replies: 5
    Last Post: 08-10-2007, 01: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
  •