given that I have a method that gets the list passed as a parameter. As part of this method, I want to use, for example, a specific ArrayList function in this list (say trimToSize ()). What will be the general approach to solving such a problem? Here are two examples:First approach (I don't think this is good)
private void doSomething(final List<T> list) { // ... do something ((ArrayList<T>) list).trimToSize(); // ... do something }
Second approach (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 am curious what is the best solution for this problem.
, - , ArrayList . ArrayList , , List. , .
ArrayList
List
private void doSomething(final ArrayList<T> list), ArrayList ?
private void doSomething(final ArrayList<T> list)
- , List, , .
ArrayList, ArrayList. , .
-, , . , , List List ArrayList, .
ArrayList .
, , ArrayLists, , List. - List, (not cast) ArrayList.
ArrayLists
, , List ArrayList ( ). , , on, .
:
, , ArrayList , trimToSize(), . , , trimToSize(), List, List.
private void doSomething(final List<T> list) { final ArrayList<T> arrayList; if (list instanceof ArrayList) { arrayList = (ArrayList<T>) list; } else { arrayList = new ArrayList<T>(list); } ... arrayList.trimToSize(); }
, : , . , .
List, , - . .
, List . API-, , .
For example, if 5 other methods call this method with potentially different types of List, use the second option and centralize the conversion in 1 method (you can even request a type and not convert if you want). If your class only deals with an ArrayList inside, and you know that this is what will happen when called, then declare it as an ArrayList and make your life easy for yourself.
Source: https://habr.com/ru/post/1733449/More articles:What can cause this problem with HTML / CSS rendering in Firefox? - htmlIs SharedCache ready for production? - performanceThe problem with updating MySQL - phpType of RDF ontology for tourism - semantic-webIs .NET double.ToString thread safe? - c #How can I execute MOSS FullTextSqlQuery and filter people's results using skill-driven? - containspython script for reliable multi-level data array on microchip - pythonWindows gadgets: how do I change the DOM? - windows-desktop-gadgetsHow to choose and configure JasperReports virtualizer? - performanceCould this work in CSS? - cssAll Articles