Java Foundation Interface Collection Framework

Source: Internet
Author: User
Tags array length comparable modifier string format

Interface
--------------------------------------------------------------------------------
One, interface (is a specification)
1. Interface name/interface files are similar to classes and are also written in. java files
2. Keyword Interface Interface name specification is the same as the class name can be used to begin with I
3. The interface amount access modifier can only be used with public and the default modifier cannot use private and protected
Default defaults to public in interface
4. All properties in an interface can only be static constants that are exposed
And public/static/final can be omitted.
5. All methods in the interface must be public abstract methods and abstract/public in abstract methods can be omitted
is still public after the omission.

--------------------------------------------------------------------------------
Implementation of class implementation interface
1. A class implements an interface using the Implements keyword
Implementing a class implements an interface that must override all abstract methods in an interface unless it is an abstract class
2. A class can implement multiple interfaces with a comma interval between multiple interfaces
3. The reference to the interface can point to the object of its implementation class. Similar to parent class references to child class objects
The interface can therefore be used to implement polymorphic
--------------------------------------------------------------------------------
Iii. Interface Inheritance Interface
1. Interface can inherit interface, use extends keyword; interface inheritance is the same as class
2. Interfaces can inherit multiple parent interfaces, use commas to split,
The child interface inherits all the abstract methods of the parent interface that will have the parent interface
--------------------------------------------------------------------------------
Four, the advantages of the interface
1. can be multiple inheritance
2. Design and achieve complete separation
3. More natural use of polypeptides
4. Easier to build a program framework
5. Easier to replace the implementation
--------------------------------------------------------------------------------
V. Differences between interfaces and abstract classes
1. Essential difference keywords different class interface
Subclass inheriting abstract class subclasses must be a class of things that must conform to the "is a" relationship
For example Chinese is peope
Interface is just an extension of functionality, when multiple implementation classes implement interfaces
Does not require all abstract classes to be a kind of thing
interface conforms to the "like a" relationship, understanding that X has an X function
Example people \ Dogs have a meal function can be realized eating interface
But the meal function cannot inherit from the same parent class
2. Abstract classes are class interfaces that are canonical
3. Interfaces can inherit interfaces and multiple-inheritance interfaces can be implemented more, but classes can inherit only one root
4. Interface can only do method declaration, abstract class can do method declaration, can also do method implementation
5. Abstract classes can guarantee the hierarchical relationship of implementation, while the pretext is the ability to more effectively separate behavior and implement
6. Abstract classes can have their own property interface intelligence has static constants
7. There are abstract methods in the interface, and abstract methods can be used in the abstraction class.
Collection Frame
Make some specifications (interfaces) and implementations for commonly used data structures and algorithms (classes that implement interfaces specifically)
--------------------------------------------------------------------------------
I. Interface of a collection frame
Collection: Store A group of objects that are not unique in order
List: Store a group of not unique ordered
Set stores a unique set of unordered objects
Map stores a set of key-valued objects that provide a key-to-value mapping (key cannot be duplicated)

--------------------------------------------------------------------------------
Second, the List of common methods (arrayslist: variable length array)

"List Interface"
1. Common methods:
①add (): add element at the end of the list;
②add (int index,e Element): Inserts an element at the specified position in the list;
③size (): Returns the number of elements in the current list;
④get (int index): Returns the element labeled Index.
If there is no generic constraint, the object type is returned, a strong turn is required, and if there is a generic constraint, the direct return of the generic type does not require a strong-go.
⑤clear (): Clears all data from the list
IsEmpty (): Detects if the list is empty
⑥contains (): Passes in an object that detects whether the object is contained in the list.
If you pass in a string and a base data type, you can directly compare the
If an entity class is passed in, the default is only the address of two objects. Therefore, the Equals () method needs to be overridden in the entity class;
Tips:
String s = "123";
= "123". Equals (s);//This order can prevent null pointers
⑦indexof (): Passes in an object that returns the address of the first occurrence of the object in the list.
Lastidexof (): Passes in an object that returns the address of the last occurrence of the object in the list.
⑧remove (): Pass in a subscript, or an object, to delete the specified element;
If the subscript is passed in, the deleted object is returned, and if the subscript is larger than size (), the subscript bounds exception is reported;
If an object is passed in, it is required to override the Equals method, which returns TRUE or false to indicate whether the deletion succeeded
⑨set (index, obj): Replaces the element at the specified position with the newly passed object;
Returns the element object that was replaced.
⑩sublist (1,3): intercepts a sub-list and returns the list type
? ToArray () Convert the list to an array returns an object type of data
--------------------------------------------------------------------------------
Third, use iterator iterator to traverse the list
1. Call with the list. Iterator () returns an Iterator object
2. Call. Hasnext () using an Iterator object to determine if there is a next piece of data
3. Use the Iterator object to invoke the. Next () to remove the next piece of data
--------------------------------------------------------------------------------
Iv. ArrayList LinkedList
1.ArrayList implements a variable-length array that opens up a contiguous set of spaces in the memory space,
The difference from an array is that the length can be arbitrarily changed,
This can only store structures in the loop and randomly access elements faster
2.LinkedList stores data using a linked list structure, and then inserts and deletes elements very quickly
Unique methods
①addfirst (): Start Insert Element
AddLast (): End insert Element
②removefirst () deletes the first element and returns the deleted element
Removelast () deletes the last element and returns the deleted element
③getfirst () returns the first element of a list without deleting
GetLast () returns the last element of the list without deleting

Set interface
1. Common methods: Basically the same as the list interface
However, because the elements in the set interface are unordered, there is no method associated with the subscript

Features of the 2.Set interface: unique, unordered

Remove Set method
Use for each to traverse
Using iterators to traverse

3.HashSet Bottom Call HashMap method to hash the data after the data is passed Hashcode
A hash value is obtained after the operation is performed to determine where the data is stored in the sequence

4.HashSet how to determine whether an object is equal
Determine whether an object's hashcode () is equal if it is not an object
If equality continues to judge the Equals () method;
Overriding the Equals () method

So when you use HashSet to store entity objects, you must override the object's Hashcode () and Equals () two methods

Linkedhashset on the basis of hashset, add a list
Use a linked list to record the order in which elements are placed in the hashset, so when iterating through an iterator, you can follow the order in which they are placed
Read out elements

Comparator needs to be implemented by a single comparison class, overriding the Compare () method, instantiating the TreeSet object, and needing to be transferred to the object of this comparison class

Map
1.Map interface features store data in key-value pairs, with key values, key cannot repeat values
2.put (key value) appends a key value to the last one
Get Value by key
Clear clears all data


The difference between HashMap and Hashtable
1. The latter thread-safe former is unsafe
2. The latter key cannot be null, the former can
The difference between HashMap and Hashtable
The main difference between the two is that Hashtable is thread safe, while HashMap is not thread safe. Hashtable implementation method inside all added synchronized keyword to ensure thread synchronization, so relatively hashmap performance will be higher, we usually use if no special needs to recommend the use of HashMap, In a multithreaded environment, using the HashMap requires the Collections.synchronizedmap () method to obtain a thread-safe collection (Collections.synchronizedmap () The implementation principle is that collections defines an inner class of Synchronizedmap, which implements the map interface, uses synchronized to ensure thread synchronization when invoking a method, and, of course, the actual operation of the HashMap instance we passed in. Simply put, the Collections.synchronizedmap () method helps us automatically add synchronized to thread synchronization when we operate HashMap. Similar other collections.synchronizedxx methods are similar in principle.
HashMap can use NULL as key, but it is recommended that you try to avoid such use. HashMap is always stored on the first node of the table array when NULL is the key. The hashtable does not allow NULL as key.
HashMap inherits the Abstractmap,hashtable inheritance dictionary abstract class, both of which implement the map interface.
The initial capacity of the HashMap is 16,hashtable with an initial capacity of 11, and the fill factor for both is 0.75 by default.
HashMap expansion is the current capacity doubling is: capacity*2,hashtable capacity is doubled +1 that is: capacity*2+1.
The underlying implementations of HashMap and Hashtable are the array + linked list structure implementations.
The two methods of calculating hash are different:
Hashtable computes a hash by directly using the hashcode of the key to directly model the length of the table array:
int hash = Key.hashcode ();
int index = (hash & 0x7FFFFFFF)% Tab.length;
HashMap calculates the hash for key hashcode two times to obtain a better hash value, and then the table array length to touch:
static int hash (int h) {
H ^= (H >>>) ^ (h >>> 12);
Return h ^ (H >>> 7) ^ (H >>> 4);
}

static int indexfor (int h, int length) {
Return H & (LENGTH-1);
}

In HashMap, NULL can be used as a key with only one key, and one or more keys can be
The expected value is null. When the Get () method returns a null value, you can either indicate that the key is not in the HashMap, or you can
To indicate that the key corresponds to a value of NULL. Therefore, the get () method cannot be used to judge Hashm in HashMap.
There is a key in the AP and should be judged by the ContainsKey () method. The Hashtable key value cannot be
Is null, so you can use the Get () method to determine if a key is contained.
Linkedhashmap
You can use a linked list to count the order in which the data is placed

Collections is a collection tool class specifically for operations in Java

Collection is an interface


Sort method sorts the data in the collection
If the collection stores a single Entity object, then
1 entity classes implement the comparable interface and override the CompareTo method
2. In the second parameter of sort, pass in the comparator, the comparator implements the comparable interface, and overrides the Compare method

"Generics"
1. Generics are "parameterized types". When you define a type, the type is not dead. Instead, they are defined in the form of generic parameters. Called when a specific generic parameter is passed in.

"Characteristics of generic classes"
When declaring a class, a generic constraint is made, such that the class is called a generic class.
Class test<t>{
<T> can be interpreted as a formal parameter in a generic declaration, and can be substituted with any letter. Common T N E
In a generic class, T can be used as a special data type
Private T Arg;
}
When a generic call is made, the actual data type needs to be passed in
test<string> test1 = new Test<string> ("Jiang Hao really handsome!" ");
test<integer> test2 = new test<integer> (123);

1. Generics only take effect during the compilation phase. The same class is judged to belong to the same class by using GetClass () objects that are obtained by different generics.
System.ou.println (test1.getclass () = = Test2.getclass ());
The class of test1 taken is the test class, not the Test<t> class

2, the same class, through the different generics get objects, incompatible with each other. Cannot assign values to each other.
Test2 = test1;//test1 incompatible with test2
3. When instantiating a generic class, you can not pass in the generic, the data type in the class, and the variable type passed in when the value is assigned is empty
4. When instantiating generics, the smart pass-through class name can be either a system class or a custom entity class


Generic wildcard upper bounds, using? The extends class name indicates that the wildcard character supports only subclasses of a specified class
Test<?extends number>tests = new test<number> ();

Generic wildcard under Bounds, using? The super class name, which indicates that wildcard characters only support the specified class and its superclass;

Generic interfaces
1. Disclaimer
Interface inter<t>{
void Test (T t);
}
2. If the implementation class implements a generic interface, then the generic type of the interface cannot be used directly, then it is necessary to re-declare
Class Test3<t> implements inter<t>{
@Override
public void Test (T t) {}
}
3. If you implement a class and do not want to be a generic class, you can assign a generic value directly to the interface when implementing the interface

Class Test3 implements inter<string>{
@Override
public void Test (String t) {}
}

Generic methods
1. You may not be able to use the generic class independently in any class in a generic class.
Class test{
public static <T> void Test (T t) {}
}
Call Test.test ("String");
2. Ways to implement variable parameters using a generic method
Class test{
/use ... Indicates that a parameter of n arbitrary type can be accepted or an array
public static <T> void Test (t......t) {}
}

Generic: Test.test ("String", "String2", 123,true)

3. Only the method of <T> is declared in the method can be a generic method
If, in a method, the generic of the usage class is not a generic method
Attention:
A static method cannot use the generic type of a class
Smart static methods are declared separately as generic methods
"Random Class"
"Random Class"
Take a random number.
Two types of construction:
① NULL parameter construction
② Pass in a seed number: As long as the number of seeds is the same, the random number taken in the same number of times must be the same. This is a pseudo-random number. The current timestamp can be passed in: System.currenttimemillis ();

Nextint (): randomly obtains an integer;
Nextint (n): Randomly obtained from the 0-n random number, containing 0 n;

"Singleton Mode"
Singleton mode: Ensures that a class can produce only one instance.

Design ideas:
① to privatize the constructor. Make sure the class is outside and you cannot create the object yourself using the New keyword.
② instantiates an object inside a class and returns it by means of a static method.


Enum Class "
An enumeration class, which is a special class.
The values inside are all static constants. Each enumeration value is equivalent to a class object, except that the object's value is the object name.
"Declaration of the enumeration class"

"Date Class"
Located under the Java.util package
Data NULL parameter construct: Fetch the current time
Data full parameter constructs: A long timestamp is passed to the specified time.

Date.gettime (): Takes a time stamp: the number of milliseconds from the 0 time zone, 1970/1/1 0:0:0 to the current time
SetTime (): Pass in a long integer to reset the date time
CompareTo (): Front > Parameter return 1 Front < parameter return-1 front = parameter return 0
Equals (): is equal to two times.
Before (): detects whether a time is before the specified time
After (): detects whether a time is after the specified time

"SimpleDateFormat"
The date is formatted under the Java.text package
When instantiating an object, pass in a formatted parameter and use the letter to represent the corresponding part
Alphabetical date or time element represents an example
Y year 1996; 96
The month in M year July; Jul; 07
Days in the D month Number 10
Number of days in E-week Text Tuesday; Tue
H hours in the day (0-23) number 0
Hours in H am/pm (1-12) Number 12
Minutes in M-hour number 30
Seconds in S minutes number 55
Format (): Used to pass in a parameter of a date type and return the formatted string
Parse (): Converts the time in string format to the date type. Requires that the passed-in string format must be exactly the same as the pattern at the time of instantiation
Topattern (): Returns the currently formatted pattern string.
"Calender Class"
The Calendar class is an abstract class that cannot be obtained directly from new and must use Calendar.getinstance (); get
GetTime Returns a Date object
Get the specified field according to the constants provided by the calendar

Java Foundation Interface Collection Framework

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.