读书笔记-ArrayList

private List<Crime> mCrimes;

 private CrimeLab(Context context) {
        mCrimes = new ArrayList<>();
        for (int i=0; i<100;i++){
            Crime crime = new Crime();
            crime.setTitle("Crime #"+i);
            crime.setSolved(i%2==0);
            mCrimes.add(crime);
        }
    }

关于这段代码书中是这样解释的:

List<E>is an interface that supports an ordered list of objects of a given type. It defines methods for retrieving, adding, and deleting elements. A commonly used implementation ofListisArrayList, which uses a regular Java array to store the list elements.
SincemCrimesholds anArrayList, andArrayListis also aList, bothArrayListandListare valid types formCrimes. In situations like this, we recommend using the interface type for the variable declaration:List. That way, if you ever need to use a different kind ofListimplementation – likeLinkedList, for example – you can do so easily.
ThemCrimesinstantiation line uses diamond notation,<>, which was introduced in Java 7. This shorthand notation tells the compiler to infer the type of items theListwill contain based on the generic argument passed in the variable declaration. Here, the compiler will infer that theArrayListcontainsCrimes because the variable declaration,private List<Crime> mCrimes;, specifiesCrimefor the generic argument. (The more verbose equivalent, which developers were required to use prior to Java 7, ismCrimes = new ArrayList<Crime>();.)

posted @ 2016-10-11 21:32  littlelionbiu  阅读(162)  评论(0编辑  收藏  举报