Java basic comparable interface, collections class, Iterator interface, generics (Generic)

Source: Internet
Author: User
Tags comparable shuffle

first, comparable interface, collections class

Common Algorithms for list:

    • Sort (List); If you need to sort your custom classes, you have to implement the comparable interface to implement a method that compares two class sizes
    • Shuffle (List); Random arrangement
    • void reverse (List); Reverse order (linked efficiency)
    • Copy (); Copy the collection, provided the size () is the same (length, and the difference in capacity)
    • Fill (List, object), use an object to populate the entire List
    • BinarySearch ();//Sort before using the binary search method

Example:

 PackageCollectiontext;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List; Public classText2 {@SuppressWarnings ("Unchecked")     Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("AAAA"); List.add ("QQQQ"); List.add ("CCCC"); List.add ("XXXX");        SYSTEM.OUT.PRINTLN (list); System.out.println ("-------------------------"); //Sequential arrangementCollections.sort (list);//Sort (List), sorting, if you need to sort your custom classes, you have to implement the comparable interface.//to implement a method that compares two class sizesSystem.out.println (list); //Random arrangementCollections.shuffle (list);//Shuffle (List); random arrangementSystem.out.println (list); //reverse arrangement (in reverse order)Collections.reverse (list);//void reverse (List); reverse order (linked more efficient)System.out.println (list); System.out.println ("-------------------------"); List List2=NewArrayList (); List2.add ("1"); List2.add ("2"); List2.add ("3"); List2.add ("4"); Collections.copy (List2, list);//copy (); Copies the collection if size () is the same (note the difference between length and capacity)System.out.println (LIST2); System.out.println ("-------------------------"); Collections.fill (List2,NewPerson ());//Fill (List, object), use an object to populate the entire ListSystem.out.println (LIST2); System.out.println ("-------------------------"); List List3=NewArrayList ();  for(inti = 0; I < 10; i++) {list3.add (i); }        intA = Collections.binarysearch (List3, 8);//BinarySearch (); It is important to note that sorting is preceded by a binary search method,//here is the order, not good-looking out, but must pay attention toSystem.out.println (a);    System.out.println (LIST3); }}classperson{@Override PublicString toString () {return"Person []"; }    }

Ii. Generics (Generic): it must be a reference type .

  1, the type of the loaded collection is treated as an object, thus losing its actual type
2, when taken out in the collection needs transformation, low efficiency, error-prone

Benefits: Enhanced readability and stability of the program

Example:

 PackageCollectiontext;Importjava.util.ArrayList;Importjava.util.List; Public classTEXT3 { Public Static voidMain (string[] args) {List<String> list =NewArraylist<string> ();//This list contains only string types.List<person2> List2 =NewArraylist<person2> ();//This list can only contain Person2 type.List<student> List3 =NewArraylist<student>(); List.add ("QQQ"); List2.add (NewPerson2 ()); List2.add (NewStudent ());//student inherits the person, the reference to the parent class, to the object of the subclass, the problem of polymorphismList3.add (NewStudent ()); }}classperson2{//defines a Person2 class, which , in a more popular way, defines a Person2 type    }classStudentextendsperson2{}
three, comparable interface: A method (Comparato)

int CompareTo (T o)

Compares this object to the specified object for sorting.

    • The object is smaller than the specified object and returns a negative integer (-1);
    • The object is equal to the specified object and returns a 0 (0);
    • The object is larger than the specified object and returns a positive integer (1);

Example:

 PackageCollectiontext;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List; Public classTEXT4 { Public Static voidMain (string[] args) {List<Animals> list =NewArraylist<animals>();  for(inti = 0; I < 5; i++) {List.add (NewAnimals ("name" + I, i+5));        } System.out.println (list);        Collections.sort (list);    SYSTEM.OUT.PRINTLN (list); }}classAnimalsImplementsComparable<animals> {    PrivateString name; Private intAge ;  PublicAnimals (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; } @Override Public intcompareTo (Animals o) {//TODO auto-generated Method Stub        if( This. Age >o.age) {            return-1; } Else if( This. Age <o.age) {            return1; } Else{            return  This. Name.compareto (O.name); }} @Override PublicString toString () {return"Animals [name=" + name + ", age=" + Age + "]"; }    }

Java basic comparable interface, collections class, Iterator interface, generics (Generic)

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.