Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method naming conventions toType and asType differences? [closed]

Tags:

java

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?

like image 982
amm Avatar asked Sep 01 '14 17:09

amm


1 Answers

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.

like image 57
Eran Avatar answered Nov 15 '22 15:11

Eran