10

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?

amm
  • 293
  • 1
  • 2
  • 13
  • Is this mean when I convert list to array converts to other type but from array to list they just wrap it. This is the part that I do not understand why they had two different way in converting between each others? – amm Sep 01 '14 at 17:42

1 Answers1

16

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • One more thing, I did not have the ability to change, I meant add new element, to the returned list it throws this error "Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:131) at java.util.AbstractList.add(AbstractList.java:91)" But you are correct I tried to add new element to the array and still I can have it in the list although I add it after the asList. – amm Sep 01 '14 at 17:56
  • It totally makes sense now, thanks a lot :-) http://stackoverflow.com/questions/18389012/how-to-add-elements-in-list-when-used-arrays-aslist – amm Sep 01 '14 at 18:01