Java Collection Framework Learning notes

Source: Internet
Author: User

This article is for the study notes, the Learning course for the Web Java introduction of the third season of the collection Framework section, if you need to study the code in the article, you can go to download. http://www.imooc.com/learn/110

1. List (Collection sub-interface) 1.1 instantiation
List list = new ArrayList();

?? A list is an interface that cannot be instantiated directly, and typically is instantiated ArrayList the implementation class.

1.2 Increment 1.2.1 Add (obj)

?? Joins the Obj object directly to the list.

1.2.2 Add (i, obj)

?? Adds the Obj object to the first bit.

1.2.3 AddAll (c)
Course[] course1 = {new Course("3","离散数学"), new Course("4","设计模式")};coursesToSelect.addAll(Arrays.asList(course1));

?? Adding multiple objects at the same time, it should be noted that the parameters of the AddAll method are collection objects, which need to be converted to collection objects through the Aslist method of the arrays class.

1.2.4 AddAll (i, C)

?? Basically the same as 1.2.3, n objects are inserted into the bits I to i+n bits.

1.3 Delete 1.3.1 Remove (obj)
Course cr = (Course) coursesToSelect.get(1);coursesToSelect.remove(cr);

?? Specify delete object directly, if the reference is different, delete fails.

1.3.2 Remove (i)

?? Deleting the I-bit object in list is better than the method in 1.3.1.

1.3.3 RemoveAll (c)

?? Similar to the AddAll method in 1.2.3.

1.4 Change (Set method)
coursesToSelect.set(0, new Course("5","计算机网络"));

?? The first parameter specifies the location of the modification, and the second is the modified content, essentially inserting a newly modified object into the specified position.

1.5 Check 1.5.1 get (i)

?? Gets the I-bit object in the list.

1.5.2 traversing the list via an iterator
Iterator it = coursesToSelect.iterator();while (it.hasNext()) {    Course cr = (Course) it.next();}
1.5.3 Traversal via For-each
for (Object obj:coursesToSelect) {    Course cr = (Course) obj;}
1.5.4 contains (obj), Containsall (c)
System.out.println("请输入要查询的课程名称:");String name = console.next();Course course2 = new Course();course2.setName(name);System.out.println("新建课程:" + course2.getName());System.out.println("备选课程中是否包含课程:" + course2.getName() + "," + coursesToSelect.contains(course2));

?? The contain method works by calling the Equals method of all objects in the list to compare with the passed arguments, and returns True if there is an object equal, or False if none.

?? It is important to note that the contains method compares not the object's value, but the object's reference, and if the reference is different, the return value is false even if the value is equal.

@Overridepublic boolean equals(Object obj) {    if (this == obj) {        return true;    }    if (obj == null) {        return false;    }    if (!(obj instanceof Course)) {        return false;    }    Course course = (Course) obj;    if (this.getName() == null) {        if (course.getName() == null)            return true;        else            return false;    } else {        if (this.getName().equals(course.getName()))            return true;        else            return false;    }}

?? To compare two objects for equality by value, you need to override the Equals method in the class to which the object resides in the list.

1.5.5 indexOf (obj), lastIndexOf (obj)

?? The former returns the index position of the first occurrence of the Obj object order, which is the reverse traversal, and returns 1 if the object does not exist in the list.

2. Set (Collection sub-interface) 2.1 instantiation
Set courses = new HashSet();

?? Instantiate through the HashSet implementation class.

2.2. Increase, delete, change, check

?? The method that needs to specify the index, the rest is basically consistent with the list.

It is important to note that the set is implemented by HashSet, so that its contains, Containsall methods remove the Equals method, and call its Hashcode method one after the other, so the Hashcode method must be overridden.

3. Map Interface 3.1 instantiation
Map<String, Student> students = new HashMap<String, Student>();

?? You need to specify the key, value, or type of the key-value pair, instantiated by HashMap.

3.2 Increase
put(key, value)
3.3 by deleting
remove(key)
3.4 Change

?? The method for modifying elements in map is put, essentially a new object that is duplicated by creating a new key value, overwriting the object that needs to be modified.

3.5 Cha 3.5.1 KeySet ()
public void testKeySet() {    //通过keySet方法,返回Map中的所有key的Set集合    Set<String> keySet = students.keySet();    System.out.println("总共有" + keySet.size() + "个学生");    //遍历keySet,取得每一个key,再调用get方法取得每个key对应的value    for (String stuId : keySet) {        Student st = students.get(stuId);        if (st != null) {            System.out.println("学生:" + st.getName());        }    }}

?? When a new set is used to host a collection returned by keyset, the type of the set is specified according to the type of key.

3.5.2 EntrySet ()
public void testEntrySet() {    Set<Entry<String, Student>> entrySet = students.entrySet();    for (Entry<String, Student> entry : entrySet) {        System.out.println("取得key:" + entry.getKey());        System.out.println("取得value:" + entry.getValue().getName());    }}

?? The collection of key-value pairs returned by this function specifies generics, and the new set collection needs to specify the generic type of entry.

3.5.3 values () (abbreviated) 3.5.4 ContainsKey (key), Containsvalue (value)

?? An object that determines whether a corresponding key value or value is present in the map.

?? It is important to note that, like the Contains method in list and set, the principles of these two methods are compared by the Equals method that calls all the elements in the map, so you need to override the Equals method.

4. Collections Tool Class 4.1 Sorting the list of integer types
List<Integer> intList = new ArrayList<Integer>();//插入10个100以内的不重复随机数Random random = new Random();Integer k;for (int i=0; i<10; i++) {    do {        k = random.nextInt(100);    } while (intList.contains(k));    intList.add(k);}System.out.println("-------排序前-------");for(Integer i : intList) {    System.out.println("元素:" + i);}Collections.sort(intList);System.out.println("-------排序后-------");for(Integer i : intList) {    System.out.println("元素:" + i);}
4.2 Sorting a list of string types
List<String> stringList = new ArrayList<String>();stringList.add("microsoft");stringList.add("google");stringList.add("lenovo");System.out.println("-------排序前-------");for(String s : stringList) {    System.out.println("元素:" + s);}Collections.sort(stringList);System.out.println("-------排序后-------");for(String s : stringList) {    System.out.println("元素:" + s);}

?? Starting from the first character, compare the second character if the first character is the same, and so on.

?? The order is: 0~9, uppercase letters, lowercase letters.

4.3 Sorting other types of lists

?? Because of the definition of the Sort method (you can refer to the official document by itself, you need to implement the comparable or comparator interface using the Sort method), you need to have the class implement the comparable interface when sorting the custom class, or a compilation error will occur.

5. Comparable interface

?? When implementing an interface, you specify the same generics as the list and implement the CompareTo method.

A.compareto (b), if a positive integer is returned, then A>b, if return 0, a is equal to B, and if return-1, then a<b.

6. Comparator interface

?? When implementing an interface, you specify the same generics as the list and implement the Compare method.
Pass

sort(List<T> list, Comparator<? super T> c)

Use.

?? Compare (A, b), if a positive integer is returned, then A>b, if return 0, a is equal to B, and if return-1, then a<b.

Java Collection Framework Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.