Java Programming Ideas (eight)--holding objects (1)

Source: Internet
Author: User
Tags addall

The original title in the book is--holding your object, which holds your object, and the translator translates it into a holding object. This is one of the most used classes.


The author says that if a program contains a fixed number of objects whose life cycle is known, this is a very simple program. Indeed, if the size of the array is known, then it is very simple.


In addition to arrays, Java provides a container class to holding object.


1) Generic and type-safe containers

ArrayList, you can automatically expand the size of an array, add Insert object, get Access object, size to view the number of objects.

Class Apple{}public class Box {public    static void Main (string[] args) {        arraylist<apple> a = new arraylist& Lt Apple> ();        A.add (New Apple ());}    }

Generics (that is, the angle brackets that follow the ArrayList indicate the Apple-type identity) can prevent objects of the wrong type from being put into the container during compilation.

Similarly, a container can also use the foreach syntax.


2) Concept

The container class action is to save the object. Divided into two:

First, the collection,list order saves the element, set cannot have the duplicate element, the queue follows the queue.

Two, MAP, key value pairs, through the key to find the value or is called a dictionary.


By the way, write so many articles, forget to say an important thing, know how to check the API documentation, it is best to look at the English version. Collection is what, class or interface, a check will know.

Public interface List<e>extends Collection<e>public class Arraylist<e>extends Abstractlist<e >implements List<e>, randomaccess, Cloneable, Serializable

This kind of relationship comes out.


3) Add a set of elements

public class AddGroup {public    static void Main (string[] args) {        collection<integer> c = new Arraylist<in Teger> (Arrays.aslist (1,2,3,4));        Integer[] group = {5,6,7,8};        C.addall (Arrays.aslist (group));        System.out.println (c);        Collections.addall (c, 9,0);        System.out.println (c);    }} [1, 2, 3, 4, 5, 6, 7, 8]//[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Collections.addall,adds all of the specified elements to the specified collection.

Add other elements to collection C, and Collection.addall is to add a set of elements.


4) Printing of containers

In fact, the above code has been shown that the specific container has implemented its own ToString method.


5) List

List has two kinds: ArrayList, random access element fast, intermediate insert and delete operation slow.

LinkedList, random access is slow, but intermediate insertions and deletions are fast, similar to linked lists.


List Common methods:

class member{int age;    Member (int i) {age = i;    } public String toString () {return ' member ' +age; }}public class Listmethod {public static void main (string[] args) {list<member> members = new arraylist& Lt        Member> ();                Member member1 = new Member (1);                add Element Members.add (member1);                Determine if the container is empty System.out.println (Members.isempty ());                Determines whether the container contains the element System.out.println (Members.contains (member1));                Display index SYSTEM.OUT.PRINTLN (members.indexof (member1));        remove element Members.remove (member1);                SYSTEM.OUT.PRINTLN (members);        Member member2 = new Member (2);        Member Member3 = new Member (3);        Member member4 = new Member (4);        Members.add (MEMBER2);        Members.add (MEMBER3);                Members.add (MEMBER4);                Similar to substring, truncated from index 0 to 1, including 0 and 1 System.out.println (members.sublist (0, 2)); MoveExcept unlike remove//removeall (collection<?> c)//remove (int index) remove (Object o) Members.remov        Eall (members);    SYSTEM.OUT.PRINTLN (members); }    }

6) iterators

The traversal is written before a useless iterator:

        for (int i = 0; i < newlist.size (); i++) {            System.out.println (Newlist.get (i));        }

while iterators are called lightweight objects, the cost of creating them is small.

        iterator<member> Iterator = Members.iterator ();        while (Iterator.hasnext ()) {            System.out.println (Iterator.next ());        }

next moves the next element, but gets the current element. Hasnext checks if there are any elements, the Iteratorf container returns a iterator.


7) Listiterator

This has not been heard before, iterator can only move forward, Listiterator can move in both directions.

        Listiterator<member> iterator = Members.listiterator ();        while (Iterator.hasnext ()) {            System.out.println (Iterator.next ());        }                while (Iterator.hasprevious ()) {            System.out.println (iterator.previous ());        }

forward output, backward output.


8) LinkedList

Insertion removal is efficient.

The method is easy to understand and belongs to the self-explanatory method name.

public class Testlinkedlist {public static void main (string[] args) {linkedlist<member> members = new Li        Nkedlist<member> ();        Member member1 = new Member (1);        Member member2 = new Member (2);        Member Member3 = new Member (3);        Members.add (Member1);        Members.add (MEMBER2);                Members.add (MEMBER3);                Returns the list header System.out.println (Members.peek ());        Remove and return the list header System.out.println (Members.removefirst ());                SYSTEM.OUT.PRINTLN (members);        Returns and removes the header System.out.println (Members.poll ());                SYSTEM.OUT.PRINTLN (members);        Removelast removal of the last Members.add (Member1);        Members.add (MEMBER2);        System.out.println (Members.removelast ());                        SYSTEM.OUT.PRINTLN (members);        AddLast and add are inserted into the end of the list of elements AddFirst natural is the table head Members.add (MEMBER2);        Members.addfirst (MEMBER2);        Members.addlast (MEMBER2); System.out.println (MEmbers); }}

9) Stack

Stack, LIFO,

In fact, with LinkedList can realize the function of the stack, push, into the time, only need to addfirst,pop, out of time, only need to Removefirst, so it reached the advanced after the


(Ten) Set

Set, elements are not duplicated.

Set and collection have exactly the same interface, but the different list, although set is collection, but the behavior is different, this is the application of polymorphism and inheritance.

public class Testset {public    static void Main (string[] args) {        set<integer> Set = new Hashset<integer> ;();        Random r = new random (+);                for (int i = 0;i<20;i++) {            set.add (r.nextint);        }        SYSTEM.OUT.PRINTLN (set);}    }

HashSet, there are no repeating elements, the order is not regular, in fact, the use of the hash, will be mentioned later.


If:

  set<integer> set = new treeset<integer> ();
can be found to be orderly, treeset the element is stored in the red black tree inside.

there was an error in the book: Linkedhashset was written as Linkedhashlist , and it also used hashing, but it seemed to use a list to maintain element insertion order.


Holding the object of this chapter is not difficult, because usually use too much, is the content of more, next will write Map,queue and summarize this chapter of things.



-------------------------alone in a foreign land for the stranger, every mid-autumn festival times Sze Chen-----------------------------






Java Programming Ideas (eight)--holding objects (1)

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.