简体   繁体   中英

How Java handles dynamic Boolean array as method parameter?

I'm using a class that has a method that accepts a boolean[] .

This code does not raise any errors

public class myclass{
    void move(boolean[] myarray) {
         //Do stufff
    }
}

Now, I do a little C++ coding, and this would not work in the context of dynamic memory.

So this is essentially a java question:

In my case the array being received has a known length, but I want to know how you would handle this in Java if it is dynamic (as well as what I should do if its not dynamic).

I'm guessing the compiler or JVM is going to handle this, but I want to know the speed optimizations I can implement.

Arrays in Java are always constant length. From The Java Tutorials , "The length of an array is established when the array is created."

If you wanted dynamic arrays, you'd use something from the Collections Framework, eg ArrayList.

In any case, a reference to the array (or collection) is passed into move(...), so there shouldn't be any difference in speed just for the function call.

When using the array, I'd expect (static) arrays to be dereferenced more quickly than going through the function calls to access elements of (dynamic) collections. However, to have a proper comparison, you'd need to provide more context of how your array is used.

You should consider using ArrayList<>() for all your needs related to iterating arbitrary length collections.

Also using List is a good practice in the Java world. There is a article about programmers who use Lists and arrays and those who use lists tend to produce less bugs.

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