I was reading Effective Java book and I had a question about the naming convention for methods, When I should use toType and asType? For example we have toString, toArray and we have asList. Why we didn't call it toList instead of using asList?
It sounds idiot question but I am just curious about the differences?
I read this from different thread, "If method returns the same instance but casted to another type, use AsXXX method. If method constructs new instance of unrelated type using object data, use ToXXX method." but why it is different from array to list and list to array in Java?
The difference between asX
and toX
can be illustrated by Arrays.asList
.
Arrays.asList
takes an array and creates a list backed by that array :
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
It doesn't create an independent list.
On the other hand, methods like toString
and toArray
create a new instance independent of the input from which it was created.
In other words, asX
takes an object of one type and creates a view of that object of a different type. toX
takes an input object and creates a new object of a different type, initialized by the input object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With