简体   繁体   中英

I thought you couldn't mix types in an array (Java)

This is more of theory question. I have this piece of code:

        String[] contacts = new String[10];

    for (int x = 0; x < contacts.length; x++)
    {
        contacts[x] = "Person" + x;
        System.out.println(contacts[x]);

    }

I understand that arrays can only have one type but I have concatenated the variable x (which is an int) on to the end of the String and stored this into an array. However when I try to do this int based array it doesn't like it which makes sense because you can't mix types in an array that is declared to be holding int variables. Im confused because you can add Boolean as well to the end of the statement.

contacts[x] = "Person" + x + false

As long as the array starts with a String you can get away with it. Is this because the String in an object itself? I'm really sorry if this is an obvious question. I believe this is related to this question but it doesn't quite answer it to my satisfaction Multiple type array

That's because if the first element is a string, then it calls toString() on x and it calls toString() on the boolean variable. So you'll just get Person1false , Person2false and so on. And they are all String .

Print them out, you'll see.

You're not adding multiple types into the array. Like in the following statement, any + operator that follows a string will concatenate the next variable as if it were parsed to a call to toString() .

contacts[x] = "Person" + x + false

So the above is the same as;

contacts[x] = "Person" + Objects.toString(x) + Objects.toString(false)

Note that in the above the variables x and the value false are auto-boxed.

Further reading;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM