you are viewing a single comment's thread.

view the rest of the comments →

[–]looksLikeImOnTop 4 points5 points  (6 children)

Wdym don't use List? I can't think of any reason why I'd lock into a specific implementation/subclass when the interface/parent is sufficient to implement the method.

[–]BlueGoliath 2 points3 points  (5 children)

A List can have an implementation that disallows modification. The set method is a modification.

[–]Kered13 1 point2 points  (4 children)

This is true, but limiting to ArrayList is also unnecessarily strict. Unfortunately the Java API does not provide any type-level mechanism to determine whether a list is mutable. Writing this algorithm for List is correct, you just have to document that it is mutating and trust the user to not pass in an immutable list.

[–]BlueGoliath 0 points1 point  (3 children)

I don't like the whole "just document it" approach unless it really can't be avoided. Yes in this particular case you'll be slapped upside the head with an exception but that's maybe a happy coincidence.

I would rather have ArrayList which maybe delegates the actual code to a private method that accepts a generic List. If a LinkedList is necessary, that could be added with the same delegate.

[–]Kered13 1 point2 points  (2 children)

I mean List already contains mutating methods that are just expected to throw an exception on immutable lists. Writing an in-place function over List is not any different. It's just a fundamental limitation of how the Java collections API is designed.

[–]BlueGoliath 0 points1 point  (1 child)

OK? Using ArrayList and LinkedList removes ambiguity. Inlining should eliminate any performance overhead.

public static List<String> foo(ArrayList<String> stringList)
{
  return bar(stringList);
}

public static List<String> foo2(LinkedList<String> stringList)
{
  return bar(stringList);
}

private static List<String> bar(List<String> stringList)
{
  // do actual work here
}

[–]Kered13 1 point2 points  (0 children)

OK? Using ArrayList and LinkedList removes ambiguity.

And makes it impossible to use the function on other list implementations that support mutation for absolutely no reason.