[JAVA & #183; elementary]: 19. Container class
Overview
A container is a collection of data.
(Java provides an interface to specifically constrain the implementation classes of our containers)
Set: does not allow duplicate objects toenter the collection of elements
SortedSet: similar to set elements t that theelements in the set are stored in ascending order
List: is ordered, maintain an order asobjects are added and removed from the collection, can also contain duplicateentries of objects
Map: stores objects that are identifiedby unique keys, and may not store duplicate keys
SortedMap: similar to Map, cannot the objectsare stored in ascending order according to their keys
That is:
? Collection interface: defines how to access a group of objects. Its Sub-interfaces Set and List define the storage methods respectively.
-The data objects in the Set are not ordered and cannot be duplicated.
-The data objects in the List are ordered and can be repeated.
-The Map interface defines how to store "key-value ing pairs.
Collection Method
? Collection indicates a group of objects. It is a set. Collection means collecting some data.
? The Collection function library is some interfaces and classes under the java. util package. Classes are used to generate objects for data storage, while interfaces are used to access data.
? The Collection function library is different from the array:
1. The size of the array is limited, but the Collection library does not have such a limit. Its capacity can be adjusted automatically.
2. The Collection function library can only be used to store objects, but arrays do not have such restrictions.
? The Collection interface is the Root Interface in the Collection hierarchy. It defines some basic access methods, so that we can access data in a unified way through it or its sub-interfaces.
? Difference: Collection represents a group of objects. The Collection function library is the Collection framework in java. The Collection interface is the Root Interface in the Collection framework.
? The data stored in the Collection library is called an element ).
Demo
public class Person { private intid; private Stringname; public Person(int id, String name) { this. id= id; this. name = name; } public intgetId() { return id; } public StringgetName() { return name; } public voidsetId (int id) { this. id= id; } public voidsetName (String name) { this.name = name; } public StringtoString() { return “id: ” + id + “|name: ” + name; }}========================================================================import java.util.*;public class CollectionTest1 { public staticvoid main (String[] args) { Collectionc = new HashSet(); c. add(new Person(1, “c++")); c. add(new Person(2, “java")); System.out.println(c. size() + ": " + c); System.out.println("contains: " + c. contains (new Person(2, "java"))); System.out.println(c. remove (new Person(2, " java"))); System.out.println(c. size() + ": " + c); }}
Output result:
Iterator Interface
? All the container classes that implement the Collection interface have an iterator method to return an object that implements the Iterator interface.
? The Iterator object is called an Iterator for convenient traversal of elements in the container.
? The Iterator interface defines the following methods:
Demo
import java.util.*;public class IteratorTest1 { public staticvoid main(String[] args) { Collectionc = new ArrayList(); c.add("good"); c.add("morning"); c.add("key"); c.add("happy"); for(Iterator it = c.iterator(); it.hasNext(); ) { Stringtem = (String) it.next(); if(tem.trim().length() <= 3) { it.remove(); } } System.out.println(c); }}
Set Method
? The Set interface is a sub-interface of the Collection interface. The Set interface does not provide additional methods. The Set interface features that the elements in the container class are unordered and cannot be repeated.
? The Set container can correspond to the concept of "Set" in mathematics.
? The Set container classes provided in J2SDK APIs include HashSet and TreeSet.
Demo
Import java. util. *; public class SetTest {public staticvoid main (String [] args) {Set s = new HashSet (); s. add ("hello"); s. add ("world"); s. add (new Integer (4); s. add (new Double (1.2); s. add ("hello"); // the same element will not be added to System. out. println (s );}}
List Interface
? The List interface is a Collection sub-interface. The elements in the container class that implements the List interface are ordered and can be repeated.
? Each element in the List container corresponds to an integer serial number that records its position in the container. You can access the elements in the container according to the serial number.
? The List containers provided by J2SDK include ArrayList and javaslist.
Demo
import java.util.*;public class ListTest { public staticvoid main(String[] argc) { List l1= new ArrayList(); for (inti = 0; i <= 5; i++) l1.add("a"+ i); System.out.println(l1); list.add(3,"a100"); System.out.println(l1); list.set(6,"a200"); System.out.println(list); System.out.print((String)list.get(2) + " "); System.out.println(list.indexOf("a3")); list.remove(1); System.out.println(list); }}
Common Algorithms
Java. util. Collections provides some static methods to implement some common algorithms based on List containers..
Demo
Import java. util. *; public class CollectionsTest {publicstatic void main (String [] argc) {List aList = new ArrayList (); for (int I = 0; I <5; I ++) aList. add ("a" + I); System. out. println (aList); Collections. shuffle (aList); // randomly arrange the System. out. println (aList); Collections. reverse (aList); // reverse System. out. println (aList); Collections. sort (aList); // sort System. out. println (aList); System. out. println (Collections. binarySearch (aList, "a2"); Collections. fill (aList, "hello"); System. out. println (aList );}}
Comparable Interface
Q: What is the above algorithm used to determine the "size" sequence of objects in a collection?
? All classes that can be sorted implement the java. lang. Comparable interface. The Comparable interface has only one method.
Public int compareTo (Objectobj );
This method:
? The class that implements the Comparable interface determines the sorting method of the class objects by implementing the comparaTo method.
Demo
public class Student implements Comparable { private Stringname; private Integerscore; publicStudent(String name, int score) { this.name =name; this.score =new Integer(score); } public intcompareTo(Object o) { Student n =(Student) o; int a =score.compareTo(n.score); return (a !=0 ? a : name.compareTo(n.name)); } public StringtoString() { return"name: " + name + " score: " + score.toString(); }}import java.util.*;public class StudentTest { public static voidmain(String[] args) { List l1 = newLinkedList(); l1.add(newStudent(“ttt", 66)); l1.add(newStudent(“bbb", 77)); l1.add(newStudent(“ccc", 99)); l1.add(newStudent(“fff", 88)); l1.add(newStudent(“aaa", 66)); System.out.println(l1); Collections.sort(l1); System.out.println(l1); }}
Map Interface
? The class that implements the Map interface is used to store key-value pairs.
? Implementation classes of the Map interface include HashMap and TreeMap.
? Key-value pairs stored in the Map class are identified by keys. Therefore, key-value pairs cannot be repeated.
Demo
import java.util.*;public class MapTest { public staticvoid main(String args[]) { Map m1 =new HashMap(); Map m2 =new TreeMap(); m1.put("one",new Integer(1)); m1.put("two",new Integer(2)); m1.put("three",new Integer(3)); m2.put("A",new Integer(1)); m2.put("B",new Integer(2)); System.out.println(m1.size()); System.out.println(m1.containsKey("one")); System.out.println(m2.containsValue(newInteger(1))); if(m1.containsKey("two")) { inti = ((Integer) m1.get("two")).intValue(); System.out.println(i); } Map m3 =new HashMap(m1); m3.putAll(m2); System.out.println(m3.size()); }}
Generic
Generics are used to constrain the type of the input object;
In general: What is passed in and what is taken out.
? Cause:
-The previous JDK1.4 type is not clear:
? The type of the loaded set is treated as an Object, thus losing its actual type.
? Transformation is often required to retrieve from a collection, which is less efficient and prone to errors.
? Solution:
-Define the object types in the collection when defining the set
? You can specify
? You can also use Iterator to specify
? Benefits:
-Enhanced program readability and Stability
Demo
import java.util.*;public class MapTest1 { public staticvoid main(String args[]) { Map
m = new HashMap
(); for(int i = 0; i < 5; i++) { m.put(String.valueOf(i),1); } for(int i = 0; i < 5; i++) { m.put(String.valueOf(i),1); } System.out.println(m.size()+ " distinct words detected:"); System.out.println(m); Set
set = m.keySet(); Iteratorit = set.iterator(); while(it.hasNext()) { System.out.println(m.get(it.next())); } }}
Enhance the for Loop
? The enhanced for loop is quite convenient for Traversing array or Collection.
? Defects:
-Array:
? Unable to easily access the tag Value
-Set:
? Compared with Iterator, it is not convenient to delete content in the set.
? Summary:
-In addition to simple traversal and reading of the content, we do not recommend using enhanced
Business Philosophy
This interface provided by JAVA specifically restricts the implementation classes of our containers, greatly reducing the burden on our designers and improving efficiency.
The summary of the container class is relatively scattered, and it is difficult to give a complete description. It can be better understood in the continuous use.