Java general interface question

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.

+3
source share
8 answers

, - , ArrayList . ArrayList , , List. , .

+12

private void doSomething(final ArrayList<T> list), ArrayList ?

+6

- , List, , .

ArrayList, ArrayList. , .

+3

-, , . , , List List ArrayList, .

ArrayList .

+2

, , ArrayLists, , List. - List, (not cast) ArrayList.

, , List ArrayList ( ). , , on, .

:

  • trimToSize() .

, , ArrayList , trimToSize(), . , , trimToSize(), List, List.

+2

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();
}

, : , . , .

+2

List, , - . .

+1

, 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.

0
source

Source: https://habr.com/ru/post/1733449/


All Articles