Day12java Basic Learning Notes

Source: Internet
Author: User
Tags array length object object

The difference between a collection/collection framework (List) array and a collection
    • Fixed array length, once defined, cannot be changed
    • Variable Set length
    • The base data type can be rough out of the array, or it can be an object (actually a reference to the object
    • Collection can only store references to objects)
Java Collection system: divided into collection and map two kinds of System collection interface

The collection has two derived interfaces: Set, List
    • Set: Features: Elements are unordered, not repeatable
    • List: Features: Elements are ordered and can be repeated
Common abstraction methods for collection interfaces
    • Boolean Add (Object O): Adds an element to the collection, returns True if added successfully, otherwise returns false
    • Boolean AddAll (Collection C): Adds all elements from another collection to the current collection, returns True if added successfully, otherwise returns false
    • void Clear (): Clears all elements in the collection and changes the set length to 0
    • Boolean contains (Object O): Returns whether the specified element is contained in the collection
    • Boolean containall (Collection C): Returns whether the collection contains all the elements contained in the set C
    • Boolean isEmpty (): Returns whether the current collection is empty
    • Iterator Iterator (): Returns a Iterator object that iterates through the elements in the collection
    • Boolean remove (Object O): Deletes the specified element in the collection C, when the collection contains one or more element C, the method only removes the first qualifying element, and the old palace delete returns true
    • Boolean RemoveAll (Collection c): Removes the element contained in collection C from the collection, which is equivalent to subtracting the collection C from the current collection, and returns True if one or more elements are deleted
    • int size (): Returns the number of elements in the collection
    • Object[] ToArray (): Converts the collection to an array when the converted array is of type Object
Iterator iterator implements collection traversal

Iterator is also a member of the collection frame, but he cannot be used to Shengzhong elements, only to traverse (that is, iterate) the elements in collection, and the iterator object is also an iterator.

If you want to use a iterator iterator, you must have a collection object, without a collection object, and the iterator is meaningless.

Common iterator methods
    • Boolean Hasnext (): To see if the collection has elements and returns false if the collection has been traversed, otherwise true
    • Object Next (): Returns the next element in the collection, noting that the back type is Object
    • Boolean remove (): Delete the last element returned, the delete succeeds return true, otherwise false

      import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class CollectionDemo {    public static void main(String[] args) {        Collection c = new ArrayList();        //给集合中添加元素        c.add("hello");        c.add(123);        c.add("asd");        c.add("hello");        c.add(new Student("张三",15));        Iterator it = c.iterator(); // 获取迭代器        while (it.hasNext()) {            Object obj =it.next();            System.out.println(obj);        }    }}
Another way to traverse a collection: Enhance A For loop

Also called the Foreach Loop, each time the loop takes the elements of the array/collection and copies them to a variable that iterates through the collection and the set

    import java.util.ArrayList;    import java.util.Collection;    import java.util.Iterator;    public class CollectionDemo {        public static void main(String[] args) {            Collection c = new ArrayList();            c.add("hello");            c.add(123);            c.add("asd");            c.add("hello");            c.add(new Student("张三",15));            for (Object obj : c) {                System.out.println(obj);            }        }    }
Attention! : When using the enhanced for traversal collection, the value passed, changing the value of the loop variable does not affect the elements in the collection, but the value of the variable can be changed.
    import java.util.ArrayList;    import java.util.Collection;    import java.util.Iterator;    public class CollectionDemo {        public static void main(String[] args) {            Collection c = new ArrayList();            c.add("java");            c.add("javaee");            c.add("javase");            for (Object obj : c) {                String name = (String)obj;//强转为String类型                name = "String"+ name;//在字符串前面加上String字样            }            System.out.println(c);// 元素并不会改变        }    }
How to delete elements from a collection in a time-elapsed time
    import java.util.ArrayList;    import java.util.Collection;    import java.util.Iterator;    public class CollectionDemo {        public static void main(String[] args) {            Collection c = new ArrayList();            c.add("hello");            c.add(123);            c.add("asd");            c.add("hello");            c.add(new Student("张三",15));            Iterator it = c.iterator();            while(it.hasNext()){                Object obj = it.next();                if(obj.equals(123)){  //调用Object类的equals()方法进行是否相等比较                    it.remove(); //这里调用Iterator的remove()方法进行删除                }            }            it = c.iterator(); //重置迭代指针,在上一轮循环中指针已指到末尾位置,重新开始遍历需要将指针重置            while (it.hasNext()) {                Object obj1 =it.next();                System.out.println(obj1);            }        }    }
List interface

is an important subinterface of the collection interface, where the elements in the collection class are ordered and repeatable, and each element in the collection has its corresponding sequential index.

The list interface implementation class has three kinds of traversal methods
    • Iterating through a collection using a iterator iterator
    • Use the For loop to iterate through the index with Get (int index)
    • Enhanced for Loop

      import java.util.List;import java.util.ArrayList;import java.util.Iterator;public class ListDemo {    public static void main(String[] args) {        // TODO Auto-generated method stub        List al = new ArrayList();        al.add("java");        al.add("javaee");        al.add("javase");        //使用Iterator迭代器遍历集合        Iterator it = al.iterator();        while(it.hasNext()){            Object obj = it.next();            System.out.println(obj);        }        //增强for循环j进行遍历        for (Object obj : al) {            System.out.println(obj);        }        //使用for循环中get(int index)通过索引来遍历        for (int i = 0; i < al.size(); i++) {            Object obj = al.get(i);            System.out.println(obj);        }    }}
The element is deleted when the collection is traversed in the list:

Reverse Traverse Delete Element

    import java.util.ArrayList;    import java.util.List;    public class RemoveDemo {        public static void main(String[] args) {            List al = new ArrayList();            al.add("java");            al.add("java");            al.add("java");            al.add("java");            //逆序遍历删除            for (int i = al.size()-1; i >=0; i--) {                String str =(String)al.get(i);                if(str.equals("java")){                al.remove(i);                }            }            System.out.println(al);        }    }
Case exercise to verify that the Equals method is called when using the Contains method
    public class Person {private String name;        private int age;        Public person () {super ();            } public person (String name, int age) {super ();            THIS.name = name;        This.age = age;        } public String GetName () {return name;        } public void SetName (String name) {this.name = name;        } public int Getage () {return age;        public void Setage (int.) {this.age = age;        } @Override Public String toString () {return ' person [name= + name + ', age= ' + Age + '] ";            } @Override public boolean equals (Object obj) {if (this = = obj) return true;            if (obj = = null) return false;            if (getclass () = Obj.getclass ()) return false;            person other = (person) obj;              if (age! = other.age)  return false;            if (name = = null) {if (other.name! = null) return false;            } else if (!name.equals (Other.name)) return false;        return true;    }} import Java.util.ArrayList;            public class Arraylistdem {public static void main (string[] args) {ArrayList Al = new ArrayList ();            person P1 = new person ("P1", 11);            person P2 = new Person ("P2", 12);            Person P3 = new Person ("P3", 13);            person P4 = new Person ("P4", 14);            Al.add (p1);            Al.add (p2);            Al.add (p3);            Al.add (p4);            For (object Object:al) {System.out.println (object);            } System.out.println ("----------");        System.out.println (Al.contains (p3)); }    }
Interview questions: A brief description of the sub-category features of list
    ArrayList:        底层数据结构是数组,查询快,增删慢。        线程不安全,效率高。    Vector:        底层数据结构是数组,查询快,增删慢。        线程安全,效率低。    Vector相对ArrayList查询慢(线程安全的)    Vector相对LinkedList增删慢(数组结构)    LinkedList:        底层数据结构是链表,查询慢,增删快。        线程不安全,效率高。    Vector和ArrayList的区别        Vector是线程安全的,效率低        ArrayList是线程不安全的,效率高    共同点:都是数组实现的    ArrayList和LinkedList的区别        ArrayList底层是数组结果,查询和修改快        LinkedList底层是链表结构的,增和删比较快,查询和修改比较慢    共同点:都是线程不安全的

List has three sons, who do we use?

    查询多用ArrayList    增删多用LinkedList    如果都多ArrayList

Day12java Basic 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.