The program always creates new objects based on certain conditions that are known to the runtime. You need to create any number of objects at any time and anywhere.
If you want to save a set of basic data type data, we recommend using an array, but the array has a fixed size.
In general, you do not know how many objects will be required when you write a program, or if you need more complex ways to store objects.
The Java Utility Class Library provides a complete set of container classes to address this problem, with the basic types being List , Set ,, Queue and Map . These object types are also known as collection classes . containers provide a perfect way to save objects .
The following is the complete container classification diagram:
1. Basic Concepts
The purpose of the Java Container Class library is to "save the object" and divide it into two different concepts:
- Collection. A sequence of independent elements.
Listelements must be saved in the order in which they are inserted, Set not repeating elements. Queuefollow the queuing rules to determine the order in which objects are produced.
- Map. A pair of "key-value pairs" objects that allow you to use keys to look up values.
//specify the exact type used when creating. list<apple> apples = new arraylist<apple> (); //Note: ArrayList has been transformed upward to list. The purpose of using the interface is that if you decide to modify your implementation, all you need is to create a change to it. //list<apple> apples = new linkedlist<apple> ();
import java.util.*; public class simplecollection {//fills a collection with an integer object and then prints all the elements in the resulting container. public static void main (string[] args) {collection<integer> c = new arraylist<integer> (); for (int i = 0 ; i < 10 ; i++) {C.add (i); //autoboxing } for (Integer i:c) {System. out . print (i + ); }}}/* Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, */ code>
Add a group of elements
import java.util.*; Public classaddinggroups { Public Static void Main(string[] args) {Collection<integer> Collection =NewArraylist<integer> (Arrays.aslist(1,2,3,4,5)); Integer[] Moreints = {6,7,8,9,Ten}; Collection.AddAll(Arrays.aslist(moreints));//Runs significantly faster, but can ' t //Construct a Collection this by:Collections.AddAll(Collection, One, A, -, -, the); Collections.AddAll(collection, moreints);//Produces a list ' backed by ' an array:list<integer> list = Arrays.aslist( -, -, -, +, -); List.Set(1, About);//OK--Modify an element, the value of list is [ +,,,] // List.add (+);//Runtime error because the underlying array cannot be resized.}}There are many practical methods in the arrays and collections classes in the Java.util package that add a set of elements to a single collection. The //arrays.aslisst () method takes an array or a comma-delimited list of elements (utility mutable arguments) and converts it to a list object.
2. Printing of containers
You must use it Arrays.toString() to produce a printable representation of the array, but the print container does not need any help.
import java.util.*;@SuppressWarnings("Rawtypes") Public classprintingcontainers {StaticCollectionFill(collection<string> Collection) {collection.Add("Rat"); Collection.Add("Cat"); Collection.Add("Dog"); Collection.Add("Dog");returnCollection }StaticMapFill(map<string,string> Map) {map.put("Rat","Fuzzy"); Map.put("Cat","Rags"); Map.put("Dog","Bosco"); Map.put("Dog","Spot");returnMap } Public Static void Main(string[] args) {System. out.println(Fill(NewArraylist<string> ())); System. out.println(Fill(NewLinkedlist<string> ())); System. out.println(Fill(NewHashset<string> ())); System. out.println(Fill(NewTreeset<string> ())); System. out.println(Fill(NewLinkedhashset<string> ())); System. out.println(Fill(NewHashmap<string,string> ())); System. out.println(Fill(NewTreemap<string,string> ())); System. out.println(Fill(NewLinkedhashmap<string,string> ())); }}/* Output:[Rat, Cat, dog, dog][Rat, Cat, dog, dog][Rat, Cat, dog][Cat, Dog, rat][Rat, Cat, dog]{rat=fuzzy, cat=rags, dog=spot}{cat=rags, dog=spot, Rat=fuzzy}{rat=fuzzy, cat=rags, dog=spot}*/
3.List
There are two types of lists:
- Basic ArrayList, which is longer than random-access elements, but is slower to insert and remove elements in the middle of a List .
- LinkedList, which provides optimized sequential access through a lower-cost insert and delete operation in the middle of the List .
function method of List
4.Set
SetDuplicate elements are not saved.
import java.util.*;publicclass SetOfInteger { publicstaticvoidmain(String[] args) { new Random(47); new HashSet<Integer>(); for(int010000; i++) intset.add(rand.nextInt(30)); System.out.println(intset); }}
5.Map
import java.util.*; Public classStatistics { Public Static void Main(string[] args) {Random Rand =NewRandom ( -); map<integer,integer> m =NewHashmap<integer,integer> (); for(inti =0; I <10000; i++) {//produce a number between 0 and: intr = Rand.Nextint( -); Integer freq = M.Get(r);//The automatic wrapper mechanism converts a randomly generated int to an integer reference that HashMap can use. M.put(r, Freq = =NULL?1: Freq +1); } System. out.println(m); }}/* Output:{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, 15=497 , 16=533, 17=509, 18=478, 19=464}*/The //key is a number generated by random, and the value is the number of times the number appears.
6.Collection and iterator
Collectionis the root interface that describes the commonality of all sequence containers.
The java.util.AbstractCollection class provides a Collection default implementation.
One reason to use the interface description is that it allows us to create more generic code.
Functional Methods of collection:
Iterators
import typeinfo.pets.*;import java.util.*; Public classsimpleiteration { Public Static void Main(string[] args) {List<pet> Pets = pets.arrayList( A);//Implementation of collection means that the iterator () method needs to be provided. Iterator<pet> it = pets.iterator(); while(it.Hasnext()) {Pet p = it.Next(); System. out.Print(p.ID() +":"+ P +" "); } System. out.println();the//foreach syntax is used primarily for arrays, but it can also be applied to any collection object. //A simpler approach, when possible: for(Pet p:pets) {System. out.Print(p.ID() +":"+ P +" "); } System. out.println();//An Iterator can also remove elements:it = pets.iterator(); for(inti =0; I <6; i++) {it.Next(); It.Remove(); } System. out.println(pets); }}/* Output:0:rat 1:manx 2:cymric 3:mutt 4:pug 5:cymric 6:pug 7:manx 8:cymric 9:rat 10:egyptianmau 11:Hamster0:rat 1:manx 2:cymric 3:mutt 4:pug 5:cymric 6:pug 7:manx 8:cymric 9:rat 10:egyptianmau 11:Hamster[Pug, Manx, Cymric, Rat, Egyptianmau, Hamster]*/
Java SE5 introduces a new called Iterable interface that contains a method that can be produced Iterator iterator() , and the Iterable interface is used by foreach to move through the sequence.
Therefore, if you create any Iterable of the implemented classes, you can use it in a foreach statement.
import java.util.*; Public classIterableclassImplementsiterable<string> {protectedstring[] Words = ("And that's how we know the Earth to be banana-shaped.").Split(" "); PublicIterator<string>iterator() {return NewIterator<string> () {Private intindex =0; Public Boolean Hasnext() {returnIndex < words.length; } PublicStringNext() {returnWords[index++]; } Public void Remove() {//Not implemented Throw NewUnsupportedoperationexception (); } }; } Public Static void Main(string[] args) { for(String s:New Iterableclass()) System. out.Print(S +" "); }}/* Output:And that's how we know the Earth to be banana-shaped.*/
In Java SE5 , a large number of classes are Iterable types, mainly including all Collection classes (but not all of them Map ).
7. Hash and hash Codes
The hashCode() default method for object is to use the address of the objects to calculate the hash code, which equals() by default is the address of the object being compared.
If you want to use your own class as HashMap the key, you must both overload hashCode() and equals() .
Related reading: What exactly is a hash?
Container classes for Java