日期:2014-05-20  浏览次数:20705 次

List vs. ArrayList
(1) List<?> myList = new ArrayList<?>();

(2) ArrayList<?> myList = new ArrayList<?>();


use (2) if code is the "owner" of the list. This is for example true for local-only variables. There is no reason to use the abstract type List instead of ArrayList. Another example to demonstrate ownership:



public class Test {

    // This object is the owner of strings, so use the concrete type.
    private final ArrayList<String> strings = new ArrayList<>();

    // This object uses the argument but doesn't own it, so use abstract type.
    public void addStrings(List<String> add) {
        strings.addAll(add);
    }

    // Here we return the list but we do not give ownership away, so use abstract type. This also allows to create optionally an unmodifiable list.
    public List<String> getStrings() {
        return Collections.unmodifiableList(strings);
    }

    // Here we create a new list and give ownership to the caller. Use concrete type.
    public ArrayList<String> getStringsCopy() {
        return new ArrayList<>(strings);
    }
}


------解决方案--------------------
然后呢?
------解决方案--------------------
我比较常用的是List<String> creditCardYears = new ArrayList<String>();