java--collection (Collection Interface), iterator, enhanced for loop, generics

Source: Internet
Author: User
Tags iterable

first, the collection

The method in the collection interface is a method that must be owned by all implementation classes in the collection.

    • ArrayList Implements List
    • List extends Collection

1. Basic Use

Other

Import java.util.arraylist;/* *  collection system, * The    target  set itself is a stored container: *       must use the collection storage Object * To       traverse the collection, take out the object *       set your own attributes */public class Arraylistdemo {public static void main (string[] args) {/* *  collection arraylist, storing int types *  Collection Does not accept the base class itself, auto-boxing stores */arraylist<integer> array = new arraylist<integer> (); Add (one); Array.add (n); for (int i = 0; i < array.  Size () ; i++) {System.out.println (array.  Get(i));} /* *  Collection stores the object of the custom person class */arraylist<person> Arrayper = new arraylist<person> (); Arrayper.add (new Person ("a", +)), Arrayper.add (New person ("B")), Arrayper.add ("C", "N"), for (int i = 0; i < arrayper.size ( ) (i++) {//get (0), the object that is taken out of the person object//is an object that must be called by ToString () System.out.println (Arrayper.get (i));}}
2. Empty the elements in the collection
/* * Collection interface method * void Clear () empties all elements in the collection * The collection container itself still exists */public static void function () {//interface polymorphic call Collection <String> coll = new arraylist<string> (); Coll.add ("abc"); Coll.add ("BCD");  System.out.println (coll); ["ABC", "BCD"]coll.clear (); System.out.println (coll);}
3. Determine if the object exists in the collection
/* * Collection Interface Method * Boolean contains (object o) determines whether an object exists in the collection, the object exists return True * method parameter is Object type */private static void Function_1 ( ) {collection<string> coll = new arraylist<string> () Coll.add ("abc"); Coll.add ("money"); Coll.add ("123"); Boolean B = coll.contains("abc"); System.out.println (b);}
4. Turn the collection into a group
  /* Collection interface method * object[] ToArray () The elements in the collection, which are converted  into an array of elements, the collection to the array *  is returned as a storage object, and the data type stored in the array is Object */ private static void Function_2 () {collection<string> coll = new arraylist<string> (); Coll.add ("abc"); Coll.add ("Itcast"); Coll.add ("Itheima"); Coll.add ("money"); Coll.add ("123"); object[] Objs = coll.toArray(); for (int i = 0; i < objs.length; i++) {System.out.println (objs[i]);}}
5. Remove Elements
/* * Collection Interface Method * Boolean remove (Object o) removes the specified element from the collection */private static void Function_3 () {collection<string> Coll = new arraylist<string> (); Coll.add ("abc"), Coll.add ("Money"), Coll.add ("money"); Coll.add ("123");  System.out.println (coll); Boolean b = coll.Remove("money"); Only the first System.out.println (b) will be removed; System.out.println (coll);}
Second, iterators

An iterator is a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence . Iterators are often referred to as "lightweight" objects because they are less expensive to create.

Iterators in the collection

Since there are many different sets in Java, we want to have a uniform way to get its value, so we have an iterator.

Interface iterator: There are two abstract methods

    • Boolean Hasnext () determines whether there are any elements in the set that can be removed, if any, returns true
    • Next () takes the next element in the collection

ArrayList override Method iterator (), returns the object of the implementation class for the Iterator interface

Iterator it = Array.iterator (), the running result is an object of the implementation class of the Iterator interface

It is an implementation class object for an interface that invokes methods Hasnext and next set element iterations

1. Basic Use
Import Java.util.arraylist;import Java.util.collection;import Java.util.iterator;public class CollectionDemo1 { public static void Main (string[] args) {//collection can store objects of any type//collection without specifying the stored data type, the collection can be saved Collection coll = new  ArrayList (); Polymorphic Coll.add ("abc"); Coll.add ("uyjgtfd");//iterators get Iterator it = Coll.iterator (); while (It.hasnext ()) {// It.next () What data type is obtained, Object class//object obj = It.next ();//system.out.println (obj); string s = (string) it.next (); System.out.println (S.length ());}}}
2. Specifying the iteration data type
public static void Main (string[] args) {collection<string> coll = new arraylist<string> (); Coll.add ("ABC1"); Coll.add ("ABC2"); Coll.add ("ABC3"); Coll.add ("ABC4");//Iterators, the method of extracting//invoking a collection of elements in a collection ArrayList () is removed, The object of the implementation class of the Iterator interface iterator<string> it = Coll.iterator ();//Interface Implementation class object, call Method Hasnext () determine whether there are elements in the collection//boolean B = It.hasnext ();//system.out.println (b);//Interface implementation class object, calling method Next () takes the element in the collection//string s = It.next ();//system.out.println (s) ;//iteration is repeated content, using loop implementation, loop condition, no element in the collection, Hasnext () returns Falsewhile (It.hasnext ()) {String s = it.next (); System.out.println (s);} /*for (iterator<string> it2 = Coll.iterator (); It2.hasnext ();  ) {//For loop implementation iterator System.out.println (It2.next ());} */}
third, enhance for loop

JDK1.5 new feature, enhanced for loop

After the JDK1.5 version, the new interface appears Java.lang.iterable,collection interface is inherited iterable

Enhanced for Loop format:

For (data type variable name: Array or collection) {

Sout (variable);

}

/* *  enhanced FOR loop traversal collection *  store custom person type */public static void Function_2 () {arraylist<person> array = new ArrayList <Person> (); Array.add (New Person ("A", "a")), Array.add (New person ("B")), and (person P:array) { SYSTEM.OUT.PRINTLN (P);}} public static void Function_1 () {//for can I invoke the object's method for the object array traversal? Of course, S is the traversed object string[] str = {"abc", "Itcast", "cn"};for (String s:str) {System.out.println (s.length ());}} /* *  implement for loop, iterate array *  benefits: Less code, easy traversal of container *  Cons: No index, cannot manipulate elements inside container */public static void function () {int[] arr = {3,1,9 , 0};for (int i:arr) {System.out.println (i+1);} System.out.println (Arr[0]);}
four, generic type

Generics are JDK1.5 new security mechanisms to ensure program security

    • Generics: Indicates the type < data type of the data stored in the collection >
public static void function () {collection<string> coll = new arraylist<string> (); Coll.add ("abc"); Coll.add ( "Rtyg"); Coll.add ("43rt5yhju");//coll.add (1);iterator<string> it = Coll.iterator (); while (It.hasnext ()) { String s = it.next (); System.out.println (S.length ());}}
1. Class with generic type
/* *  with generic class *    ArrayList *    e:element element, the actual thought is just a variable  *    arraylist<integer>, E accepts the type, is the integer type * Public    class arraylist<e>{*     * Public       boolean Add (integer E) {*          elementdata[size++ ] = e; *       } *        Public       boolean add (E e) {} *    } *     *    iterator<e>  *    E Next () *     *    iterator<integer>  *    Integer Next () *    */public class GenericDemo1 {public static void main ( String[] args) {arraylist<integer>  array = new arraylist<integer> (); Array.add (123); Array.add (456) ;//ArrayList collection, own a method//<T> t[] ToArray (t[] a) integer[] i = new integer[array.size ()];integer [] j = Array.toarray (i); for (Integer k:j) {System.out.println (k);}}}
2, the interface with the generic type
public static void function () {collection<string> coll = new arraylist<string> (); Coll.add ("abc"); Coll.add ( "Rtyg"); Coll.add ("43rt5yhju");//coll.add (1);iterator<string> it = Coll.iterator (); while (It.hasnext ()) { String s = it.next (); System.out.println (S.length ());}}
3. Wildcard character of generic type
Import Java.util.arraylist;import java.util.collection;import java.util.hashset;import java.util.Iterator;/* *  Generic wildcard */public class Genericdemo {public static void main (string[] args) {arraylist<string> array = new ARRAYLIST&L T String> (); hashset<integer> set = new Hashset<integer> (), Array.add ("123"), Array.add ("456"); Set.add (789); Set.add ( 890); iterator (array); iterator (set);} /* *  define method, you can iterate over 2 sets *  parameters: How to implement, cannot write ArrayList, can not write HashSet *  parameters: or the common implementation of the interface *  generic wildcard, matching all data types  ? */ public static void iterator (collection<?> coll) {iterator<?> it = Coll.iterator (); while (It.hasnext ()) {// It.next () Gets the object, what type System.out.println (It.next ());}}}
4. Example
/* * Will the hotel staff, cooks, waiters, managers, respectively stored in 3 sets * Define the method, you can traverse 3 sets simultaneously, traverse three sets simultaneously, can call the working method */import Java.util.arraylist;import Java.util.iterator;public class Generictest {public static void main (string[] args) {//Create 3 Collection objects Arraylist<chushi> CS = new arraylist<chushi> (); Arraylist<fuwuyuan> fwy = new arraylist<fuwuyuan> (); arraylist<jingli> JL = new arraylist<jingli> ();//each collection stores its own element Cs.add (new Chushi ("Zhang San", "Rear chef 001")); Cs.add (new Chushi ("John Doe", "002"), Fwy.add (New Fuwuyuan ("Cui Hua", "Service 001")), Fwy.add (New Fuwuyuan ("Sauerkraut", "service 002"); Jl.add (New Jingli ("nickname", "Board of Directors 001", 123456789.32)); Jl.add (New Jingli ("Xiao Qiang", "board 002", 123456789.33));//arraylist<string> arraystring = new Arraylist<string> ( ); iterator (JL); iterator (Fwy); iterator (CS); /* Define method, you can traverse 3 sets at the same time, traverse three sets simultaneously, can invoke working method work *? Wildcard, iterator It.next () method takes out the object type, how to invoke the Work method * Cast: It.next () =object o ==> Employee * method Parameters: Control, you can pass the Employee object, You can also pass an employee's subclass of Object * Generic to qualify this case, parent class fixed employee, but subclass can be unlimited? *   ? Extends Employee limit is parent class, upper limitQualified, can pass employee, pass his subclass object *? Super Employee restricts the subclass, the lower bound, can pass the Employee, passing his parent class object */public static void iterator (ARRAYLIST&LT;? extends employee> arr ay) {iterator< extends employee> it = Array.iterator (); while (It.hasnext ()) {//Gets the next () data type, what is the Employee Employee e = It.next (); E.work (); }}}

java--collection (Collection Interface), iterator, enhanced for loop, generics

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.