Java Collection framework 1, java Collection framework

Source: Internet
Author: User
Tags addall

Java Collection framework 1, java Collection framework
1. Summary

All collection classes are located under the java. util package. Only objects can be saved in the collection (the referenced variables of objects are saved ). (Arrays can save basic data or objects ).

When we put an Object into a collection, the system treats all the collection elements as instances of the Object class. After JDK1.5, this state has been improved: You can use generics to restrict the types of elements in the set and let the set remember the types of all the set elements (see the specific generic content ).

Java's Collection classes are derived from two interfaces: Collection and Map. Collection and Map are the root interfaces of the Java Collection framework. These two interfaces contain some interfaces or implementation classes.

The Set and List interfaces are two subinterfaces derived from the Collection interface, and the Queue is the Queue implementation provided by Java, similar to the List.

Map implementation class is used to save key-value data with ing relationships ).

Set, List, and Map can be viewed as three types of sets.

The List set is an ordered set. The elements in the set can be repeated. The elements in the access set can be accessed Based on the element index.

The Set is an unordered Set. Elements in the Set cannot be repeated. Elements in the Set can only be accessed Based on the element itself (which is also the reason why the elements in the Set cannot be repeated ).

Elements in the form of Key-value pairs stored in the Map set can only be accessed based on the key of each element.

For Set, List, and Map sets, the most common implementation classes are HashSet, ArrayList, and HashMap.

2. Collection Interface

The Collection interface is the parent interface of the List, Set, and Queue interfaces. You can also operate these three interfaces.

You can refer to the API documentation for details about how the Collection interface defines the operation of Collection elements. Collection is an object group with independent elements and usually has the same rules.

Basic operations:

Add element add (Object obj); addAll (Collection c );

Delete element remove (Object obj); removeAll (Collection c );

Returns the intersection retainAll (Collection c );

Delete element remove (Object obj); removeAll (Collection c );

Returns the intersection retainAll (Collection c );

 

The three specific classes of the Set interface are:

HashSet -- Based on the hash set, the hashCode () method must be implemented for the elements added to the hash list.

LinkedHashSet -- Return elements in the order of adding when the set is iterated

TreeSet -- Data Structure Based on (balance) Tree

Hash set

1. Inheritance Structure
Java. lang. Object
| _ Java. util. AbstractCollection <E>
| _ Java. util. AbstractSet <E>
| _ Java. util. HashSet <E>

2. Main Methods
Add (Object)
AddAll (Collection)
Remove (object)
RemoveAll (Collection)
Size ()
Iterator ()
ToArray ()
Clear ()
IsEmpty ()
Contain (object)
ContainAll (Collection)

Identical items are not allowed in the Set. When the Set uses the Add () method to Add a new item, it first calls equals (Object o) to compare whether a new item and an existing item are equal, rather than using = to determine equality. Therefore, for classes with the string and other methods that have overwritten the equals method, the equality is compared by value.

The following program creates a hash set to store strings and uses an iterator to traverse the elements in this rule set:

public class Main{    public static void main(String args[]) {        Set<String> set = new HashSet<String>();        set.add("London");        set.add("Paris");        set.add("New York");        set.add("New York");        set.add("Beijing");        set.add("Guangzhou");        System.out.println(set);                Iterator<String> iterator = set.iterator();        while(iterator.hasNext()) {            System.out.print(iterator.next().toUpperCase() + " ");        }    }}

Note: strings are not stored in order, because the elements in the hash are not in a specific order.

You can also use the for-each loop instead of the iterator to simplify the above iteration code:

for(Object i: set)    System.out.print(i);

Since a rule set is an instance of Collection, all methods defined in Collection can be used in the rule set. The following code is an example:

Public class Main {public static void main (String args []) {Set <String> set1 = new HashSet <String> (); set1.add ("London "); set1.add ("Paris"); set1.add ("New York"); set1.add ("San Francisco"); set1.add ("Beijing"); set1.add ("Guangzhou"); System. out. println (set1); System. out. println (set1.size () + "elements in set1"); set1.remove ("London"); System. out. println ("\ nset1 is" + set1); System. out. println (set1. Size () + "elements in set1"); Set <String> set2 = new HashSet <String> (); set2.add ("London"); set2.add ("Shanghai "); set2.add ("Paris"); System. out. println ("\ nset2 is" + set2); System. out. println (set2.size () + "elements in set2"); System. out. println ("\ nIs Taipei in set2? "+ Set2.contains (" Taipei "); set1.addAll (set2); System. out. println ("\ nafter adding set2 to set1, set1 is" + set1); set1.removeAll (set2); System. out. println ("After removing set2 from set1, set1 is" + set1); set1.retainAll (set2); // retain the common element System. out. println ("After removing common elements in set2" + "from set1, set1 is" + set1 );}}

The running result is as follows:

[San Francisco, New York, Guangzhou, Paris, Beijing, London]
6 elements in set1

Set1 is [San Francisco, New York, Guangzhou, Paris, Beijing]
5 elements in set1

Set2 is [Shanghai, Paris, London]
3 elements in set2

Is Taipei in set2? False

After adding set2 to set1, set1 is [San Francisco, New York, Guangzhou, Shanghai, Paris, Beijing, London]
After removing set2 from set1, set1 is [San Francisco, New York, Guangzhou, Beijing]
After removing common elements in set2 from set1, set1 is []

Chained hash set -- custom hashset

LinkedHashSet, as its name implies, adds Linked support to the implementation of Hash. For LinkedHashSet, a linked list is connected to each node to ensure the order of determination. You can directly use the LinkedHashSet when you want to require efficient access performance with constant complexity and sorting at the same time.

LinkedHashSet uses a linked list to extend the HashSet class. It supports sorting of elements in the rule set. Elements in a HashSet are not sorted. It implements the Set interface. Each element stored in the Set must be unique because the Set does not store duplicate elements. However, the Set interface does not guarantee the order of elements to be maintained. Set and Collection have the same interface Iterable, and Set inherits Collection. LinkedHashSet has the query speed of HashSet and maintains the element Order (insertion order) using the linked list internally. Therefore, when the iterator is used to traverse the Set, the result is displayed in the order of element insertion.
The following is a test program:

public class Main{    public static void main(String args[]) {        Set<String> set = new LinkedHashSet<String>();        set.add("London");        set.add("Paris");        set.add("New York");        set.add("San Francisco");        set.add("Beijing");        set.add("New York");                System.out.println(set);        for(Object i: set)            System.out.print(i.toString().toLowerCase() + " ");    }}

If you do not need to maintain the sequence in which elements are inserted, you should use HashSet, which is more efficient than HashSet.

TreeSet

Inheritance structure:

Java. lang. Object
| _ Java. util. AbstractCollection <E>
| _ Java. util. AbstractSet <E>
| _ Java. util. TreeSet <E>

Class declaration:
Public class TreeSet <E>
Extends AbstractSet <E>
Implements SortedSet <E>, Cloneable, java. io. Serializable // it implements sortedSet and has the sorting function.

Main Properties of TreeSet

1. duplicate elements cannot exist in TreeSet;

2. TreeSet has the sorting function;

3. The elements in the TreeSet must implement the Comparable interface and rewrite the compareTo () method. This method is used to determine whether the elements are repeated and determine the order of the elements;

4. For classes defined in java class libraries, TreeSet can store them directly, such as String and Integer (because these classes have implemented the Comparable Interface );

Common java classes implement the Comparable interface and provide a relatively large standard. Common classes for implementing the Comparable interface:

  • BigDecimal, BigIneger, and all numeric corresponding packaging classes: Compare them by their corresponding values.

  • Character: Compare the Character UNICODE values.

  • Boolean: the package class instance corresponding to true is greater than false.

  • String: Compare the UNICODE values of the characters in the String.

  • Date and Time: the subsequent Time and Date are larger than the previous Time and Date.

Public class Main {public static void main (String args []) {Set <String> set = new HashSet <String> (); set. add ("London"); set. add ("Paris"); set. add ("New York"); set. add ("San Francisco"); set. add ("Beijing"); set. add ("New York"); TreeSet <String> treeSet = new TreeSet <String> (set); System. out. println ("Sorted tree set:" + treeSet); // The following method is used in the SortedSet interface System. out. println ("first ():" + treeSet. first (); // returns the first element System. out. println ("last ():" + treeSet. last (); // returns the last element System. out. println ("headSet ():" + treeSet. headSet ("New York"); // returns all elements before New York, System. out. println ("tailSet ():" + treeSet. tailSet ("New York"); // returns all elements of New York and later. // use the method System in the NavigableSet interface. out. println ("lower (\" p \ "):" + treeSet. lower ("P"); // returns the largest element less than "P" System. out. println ("higher (\" p \ "):" + treeSet. higher ("P"); // returns the smallest element System greater than "P. out. println ("floor (\" p \ "):" + treeSet. floor ("P"); // returns the largest element of System less than or equal to "P. out. println ("ceiling (\" p \ "):" + treeSet. ceiling ("P"); // return the minimum element System greater than or equal to "P. out. println ("pollFirst (\" p \ "):" + treeSet. pollFirst (); // Delete the first element and return the deleted element System. out. println ("pollLast (\" p \ "):" + treeSet. pollLast (); // Delete the last element and return the deleted element System. out. println ("New tree set:" + treeSet );}}

The running result is as follows:

Sorted tree set: [Beijing, London, New York, Paris, San Francisco]
First (): Beijing
Last (): San Francisco
HeadSet (): [Beijing, London]
TailSet (): [New York, Paris, San Francisco]
Lower ("p"): New York
Higher ("p"): Paris
Floor ("p"): New York
Ceiling ("p"): Paris
PollFirst ("p"): Beijing
PollLast ("p"): San Francisco
New tree set: [London, New York, Paris]

Comparator interface Comparator

Sometimes you want to insert elements into a tree set. These elements may not be java. lang. Comparable Instances. In this case, you can define a comparison container to compare these elements.

The Comparetor interface has two methods: compare and equals.

Public int compare (Object element1, Object element2 );

If element1 is less than element2, a negative value is returned. If it is greater than, a positive value is returned. If it is equal, 0 is returned;

Public boolean equals (Object element );

If the specified object is also a comparator and has the same sorting as this comparator, true is returned.

public class Main{    public static void main(String args[]) {        Person a[] = new Person[4];        a[0] = new Person("zhangsan", 11);        a[1] = new Person("lisi", 23);        a[2] = new Person("wangwu", 33);        a[3] = new Person("wuzhong", 26);        compareName cn = new compareName();        compareAge ca = new compareAge();        for(int i = 0; i < a.length; i++) a[i].print();        System.out.println();        System.out.println("sorting by age:");        Arrays.sort(a, ca);        for(int i = 0; i < a.length; i++) a[i].print();        System.out.println();        System.out.println("sorting by name:");        Arrays.sort(a, cn);        for(int i = 0; i < a.length; i++) a[i].print();    }}class Person {    public String name;    public int age;    Person(String n, int a) {        name = n;        age = a;    }    public void print() {        System.out.println("Name is " + name + ", Age is " + age);    }}class compareAge implements Comparator<Person> {    public int compare(Person p1, Person p2) {        if (p1.age > p2.age)  return -1;        else if (p1.age < p2.age) return 1;        else return 0;    }}class compareName implements Comparator<Person> {    public int compare(Person p1, Person p2) {        return p1.name.compareTo(p2.name);    }}

Running result:

Name is zhangsan, Age is 11
Name is lisi, Age is 23
Name is wangwu, Age is 33
Name is wuzhong, Age is 26

Sorting by age:
Name is wangwu, Age is 33
Name is wuzhong, Age is 26
Name is lisi, Age is 23
Name is zhangsan, Age is 11

Sorting by name:
Name is lisi, Age is 23
Name is wangwu, Age is 33
Name is wuzhong, Age is 26
Name is zhangsan, Age is 11

 


What is the java Collection framework?

Java is a general term for Java programming language and Java platform launched by Sun Microsystems in May 1995. The Java-based HotJava browser (supporting Java applet) shows the charm of Java: cross-platform, dynamic Web and Internet computing. Since then, Java has been widely accepted and promoted the rapid development of Web. common browsers now support Java applet. A collection framework is a unified standard architecture defined for the expression and operation set. Any collection framework contains three main parts: External interfaces, interface implementation, and set calculation algorithms.

What is the java Collection framework?

The Java platform provides a new collection framework. The set framework consists of a group of interfaces used to operate objects. Different Interfaces describe a set of different data types.

Framework of Java 2 sets

Set interface: Six interfaces (short dotted line), indicating different set types, is the basis of the set framework.

Abstract class: Five abstract classes (long dotted line) are used to implement part of the set interface. Can be expanded to custom collection classes.

Implementation class: Eight implementation classes (Real-line representation), specific implementation of the interface.

To a large extent, once you understand the interface, you understand the framework. Although you always need to create interface-specific implementations, the methods used to access the actual set should be restricted to the use of interface methods. Therefore, you can change the basic data structure without changing other code.

· The Collection interface is a set of objects that can be repeated.

· The Set interface inherits collections but does not allow repeated operations. It uses an internal arrangement mechanism.

· The List interface inherits Collection objects and allows repeated elements to be placed in the order of element insertion without re-arrangement.

· The Map interface is a key-value object consisting of a pair, that is, it holds key-value pairs. Duplicate keys are not allowed in Map. Has its own internal arrangement mechanism.

· The Element Types in the container are all objects. When getting an element from a container, you must convert it to the original type.

Java 2 simplified set framework

Set Interface

1. Collection Interface

Indicates any object or element group. This interface is used when you want to process a group of elements in a regular way as much as possible.

(1) add or delete a single element:

Boolean add (Object o): adds an Object to a set.

Boolean remove (Object o): If the set contains objects that match o, delete the Object o

(2) query operations:

Int size (): returns the number of elements in the current set.

Boolean isEmpty (): determines whether any element exists in the set.

Boolean contains (Object o): searches for whether the set contains Object o

Iterator iterator (): returns an Iterator used to access each element in the set.

(3) group operation: acts on the element group or the entire set.

Boolean containsAll (Collection c): checks whether the Collection contains all elements in set c.

Boolean addAll (Collection c): Adds all elements in set c to this set.

Void clear (): deletes all elements in a collection.

Void removeAll (Collection c): removes all elements in Collection c from the Collection.

Void retainAll (Collection c): Removes elements not included in set c from set

(4) convert Collection to Object array:

Object [] toArray (): returns an array containing all elements of the set.

Object [] toArray (Object [] a): returns an array containing all elements of the set. The array and parameter a returned at runtime are of the same type and must be converted to the correct type .... Remaining full text>

Related Article

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.