Results 1 to 4 of 4
  1. #1
    gunitinug is offline Member
    Join Date
    Dec 2016
    Posts
    13
    Rep Power
    0

    Default Assigning Integer to Number fails

    Java Code:
    import java.util.*;
    
    public class Test {
      public static void main(String[] args) {
        List<Integer> l = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        Number n = new Integer(6);
        l.add(n);
      }
    }
    This fails. If I change to
    Java Code:
    Integer n = new Integer(6);
    it works.

    Explain?

    Java Code:
    import java.util.*;
     
    public class Test {
      public static void main(String[] args) {
        List<Integer> l = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        Number n = new Integer(6);
        l.add((Integer)n);
        System.out.println(Arrays.toString(l.toArray()));
      }
    }
    This works.
    The change was type caste to Integer.
    Java Code:
    l.add((Integer)n);
    Last edited by gunitinug; 05-11-2017 at 05:25 AM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Assigning Integer to Number fails

    If you post the compiler error message we can explain it to you.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Assigning Integer to Number fails

    Here's a hint (but not much of one).

    Imagine that Number is a bucket and you have two of them.
    In one bucket you have water. In the other you have gasoline (or petrol).
    And you can't tell the difference.
    Which bucket with 100% certainty are you going to throw on the fire to help put it out?

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Assigning Integer to Number fails

    Putting out fires with gasoline?
    There's a song in there somewhere.
    ;)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Number and Integer
    By suhaas_mohandos in forum New To Java
    Replies: 7
    Last Post: 04-02-2014, 02:53 PM
  2. Replies: 2
    Last Post: 03-17-2014, 01:51 AM
  3. Replies: 3
    Last Post: 11-23-2010, 02:19 PM
  4. Replies: 0
    Last Post: 11-23-2010, 12:32 PM
  5. Replies: 0
    Last Post: 04-06-2008, 07:40 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
  •