General Java questions about interfaces

Consider that I have a method that passes list as a parameter In this method, I want to use a specific function such as ArrayList (such as trimtosize()) in the list What is the general way to deal with such a problem?

private void doSomething(final List<T> list) {
  // ... do something
  ((ArrayList<T>) list).trimToSize();
  // ... do something
}

The second method (I think this is better)

private void doSomething2(final List<T> list) {
final List<T> myList = new ArrayList<T>();
// Collections.copy(myList,list); or
myList.addAll(list);
((ArrayList<T>) myList).trimToSize();
//..do something
}

I wonder what the best solution to the problem is

Solution

Well, the preferred option is to first write a method to get ArrayList If you need ArrayList specific functionality, this method does not need to use list Transfer responsibility for ensuring that the parameter is of the correct type to the caller and do not mess with it within the method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>