Reassigning an entire Array. How?

edited December 2014 in Questions about Code

When I enter something like this:

int[] list = {0,0,0};
list = {1,0,0};

I get the error message: unexpected token: {

How do I reassign everything in an array. I could not find the answer to this in a search/ didn't know how to search for it.

Tagged:

Answers

  • edited December 2014
    list[0]=1;
    list[1]=0;
    list[2]=0;
    

    ;-)

  • edited December 2014

    or in using a for-loop when we have mostly the same number or there's a formula we can use

    for (i = 0; i < list.length; i++) 
        list[i] = 13 + i * 5; 
    

    ;-)

  • edited December 2014 Answer ✓

    In Java, shortcut array instantiation w/ just {} is only valid when we're also declaring a variable for it.
    Re-assignment demands new + explicit array type before the {}: :(

    int[] nums = {10, 20, 30};
    println(nums);
    println();
    
    nums = new int[] {15, 5, -40, 1000};
    println(nums);
    
    exit();
    
  • Ha! Great. I didn't know this! Thank you. ;-)

  • Thanks guys!

    I was using the first solution you gave me Chrisir, but was looking for something a bit cleaner. Glad to know I can change t

Sign In or Register to comment.