Dark Horse Programmer--java Basic---collection Framework tool class

Source: Internet
Author: User
Tags comparable sorts

Dark Horse programmer--java Basic <a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! ------

I. Overview

Java provides a range of tool classes for manipulating set, list, and map, mainly collections and arrays. The features of the two tool classes are: The methods in the class are static, and you do not need to create the object and call it directly using the class name. Collections: is a tool class for collection objects, provides a tool method for manipulating collections, and Arrays: is an array of tool classes that provide a tool method for arrays.
When you convert an array to a collection, you can use the collection method to manipulate the collection, but some methods of changing the set length cannot be used because the array is fixed-length.
When an element in an array is a reference data type, the elements in the array are present as elements in the collection after it becomes a collection.
When an element in an array is a base data type, the array becomes the element in the collection after it becomes a collection.

First, the text

1 , Collections Tool Class

In the Collections tool class, many methods are used to manipulate the list collection, such as comparisons, lookups, random sorting, etc., and the following are common methods:

1. Find: T max (Collection<? Extends t>Coll) gets the largest element in the Coll collection, based on the natural order of the collection, T Max (Collection<? Extends T> coll,comparator<? Super t>comp) Gets the maximum element Int BinarySearch (lsit) in the Coll collection according to the order of the specified comparator comp.<? Extends Comparable<? Super t>>list,tkey) binary search for the specified object in the list collection2. Replace:voidFill (list<? Super T>list, T obj) replaces all elements in the list collection with the specified object, obj boolean replaceall (list<T>lsit,t oldval,t newval) Replace oldval values in the list collection with newval3. Reverse reverse (List<?>list) Reverses the order of the elements in the list collection Comparator Reverseorder () returns a comparer that forcibly reverses the natural order of the objects that implement the comparable interface Comparator Reverseord ER (Comparator<T>CMP) Returns a comparer that forcibly reverses the order of the specified comparer4. Sort:voidShuffle (list<?>list) Randomly sorts the elements in the list collection using the default random sourcevoidSort (lsit<t>list) Sorts the elements in the list collection according to the natural ordervoidSort (list<t> lsit,comparator<? super t> C) sorts the List collection according to the ordering of the specified comparer C

Here is a practice code:

 Public classUser {//no need to implement comparable interface here    PrivateString name; PrivateInteger Order;  PublicString GetName () {returnname; }
Public voidsetName (String name) { This. Name =name; }
PublicInteger GetOrder () {returnorder; }
Public voidSetorder (Integer order) { This. Order =order; }} in the main class, you can write: Public classtest{ Public Static voidMain (string[] args) {User user1=NewUser (); User1.setname ("a"); User1.setorder (1); User User2=NewUser (); User2.setname ("b"); User2.setorder (2); List<User> list =NewArraylist<user>(); List.add (User2); List.add (user1);
Collections.sort (list,NewComparator<user>(){ Public intCompare (user arg0, user arg1) {returnArg0.getorder (). CompareTo (Arg1.getorder ());    } }); for(User u:list) {System. out. println (U.getname ()); } }}

The above program shows how to sort the list by using the collections sorting method.

2 , Arrays Tool Class

the Java.util.Arrays class makes it easy to manipulate an array, and all of the methods it provides are static. Has the following features:

1. Assign a value to the array: through the Fill method.

2. Sort an array: By the Sort method, in ascending order.

3. Compare arrays: Compares the values of elements in an array by the Equals method.

4. Find array elements: The BinarySearch method can be used to perform binary search of sorted arrays.

The following are the specific application codes for common methods:

public class Testarrays {

public static void output (Int[] array) {

if (array!=null) {

for (int i = 0; i < Array.Length; i++) {

System.out.print (array[i]+ "");

}

}

System.out.println ();

}

public static void Main (string[] args) {

int[] array = new INT[5];

Populating an array

Arrays.fill (array, 5);

System.out.println ("padding array: Arrays.fill (Array, 5):");

Testarrays.output (array);

Assigns the 2nd and 3rd elements of an array to a value of 8

Arrays.fill (Array, 2, 4, 8);

SYSTEM.OUT.PRINTLN ("assigns the 2nd and 3rd elements of the array to 8:arrays.fill (array, 2, 4, 8):");

Testarrays.output (array);

Int[] array1 = {7,8,3,2,12,6,3,5,4};

Sort from 2nd to 6th of an array

Arrays.sort (array1,2,7);

System.out.println ("Sort the 2nd to 6th elements of an array: Arrays.sort (array,2,7):");

Testarrays.output (array1);

To sort the entire array

Arrays.sort (array1);

System.out.println ("Sort the entire array: Arrays.sort (array1):");

Testarrays.output (array1);

Compare array elements for equality

System.out.println ("Compare array elements for equality: arrays.equals (Array, array1):" + "\ n" +arrays.equals (array, array1));

int[] Array2 = Array1.clone ();

System.out.println ("The array elements are equal after cloning: Arrays.equals (Array1, Array2):" + "\ n" +arrays.equals (Array1, array2));

Use a binary search algorithm to find the subscript where the specified element is located (must be ordered, otherwise the result is incorrect)

Arrays.sort (array1);

System.out.println ("element 3 in array1 position: Arrays.binarysearch (Array1, 3):" + "\ n" +arrays.binarysearch (Array1, 3));

Returns a negative number if it does not exist

System.out.println ("element 9 in array1 position: Arrays.binarysearch (array1, 9):" + "\ n" +arrays.binarysearch (Array1, 9));

}

}

Note: to convert an array to a collection, you cannot use the add and subtract methods of the collection, because the length of the array is fixed, and if the additions and deletions are made, the Unsupportedoperationexception compilation exception is generated.

3 , jdk1.5 new Features

The collection has a parent interface iterable that encapsulates the iterator method and provides an enhanced for loop with the following format:

 for (element type variable: Array or Collection collection) {}

Enhanced for loop and traditional for loop differences: Enhanced for loop, when used, must have traversed target, and can only traverse the array and collection collection, simplifying the iteration; traditional for loop, use more common.

Note: iterating through an array or using a traditional for loop allows you to manipulate the elements in the arrays by pointers

A mutable parameter is a specified data type followed by a three point, which is actually an array of type parameters, previously defined a int[] type parameter, the call must be defined good one array, and then passed in. And now define an int ... parameter of type, the caller, passing the element directly into the function, at run time, will automatically encapsulate these actual parameters into an array of that type.

Note: If there are multiple arguments on the function, the mutable parameter must be defined at the last edge of the argument list, otherwise the compilation fails

Iii. Summary

This article describes the two tool classes of the collection framework, as well as the two new features of jdk1.5. The basic use of collections and arrays is simply described, where collections writes a simple instance of sort.

Dark Horse Programmer--java Basic---collection Framework tool class

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.