Application examples of generics in Java

Source: Internet
Author: User


Package example6;

Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.HashSet;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.Set;

Import Org.junit.Test;


/*1. Why use generics?
* Generally used on the set, for example, now put a string type in the collection, this time, the character put into the collection will lose its own type, can only be object type, for example, want to convert this value,
* Type conversion errors are prone to occur. You can use generics to solve this problem.
* Common collection: List set map
* List of three implementations (ArrayList LinkedList vector)
* The difference between the three:
* 1. These three classes implement the list interface, where elements stored in these two collections are linklist, and the underlying data structure is a list structure.
* Both 2.ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, both of which allow the element to be indexed directly by ordinal, with fast query speed,
* But inserting elements involves memory operations such as array element movement, so indexing data is fast and inserting data is slow.
* 3.LinkedList using a bidirectional linked list for storage, index data by ordinal need forward or backward traversal, but when inserting data only need to record the item before and after items, so insert, modify, delete faster.
* 4.Vector is synchronous processing, the performance is low; ArrayList is the use of asynchronous processing, high performance.
* 5.Vector is thread-safe, ArrayList is non-thread safe. LinkedList is non-thread safe.
* 6. In general, arraylist,arraylist occupy a small amount of memory, if you just look for elements in a specific location or only add and remove elements at the end of the collection, you can use either a vector or a ArrayList.
* If it is an insert or delete operation for other specified locations, it is best to select LinkedList.
*
* Note: In generics, you must write an object, such as a string, that cannot write basic data types, such as int.
* To write the basic data type corresponding to the wrapper class
* Byte---Byte
* INT---Integer
* Short---
* Loong---Long
* Float---float
* Double---double
* Boolean---Boolean
* Char---character
* */

public class Fanxing {
Generics are used on set sets
@Test
public void setlist () {
set<string> set = new hashset<string> ();
Set.add ("Baojuan");
Set.add ("Xinxin");
Set.add ("Xuanxuan");
There are only two ways to traverse the Set collection (iterators, enhanced for)
for (String S1:set) {
System.out.println (S1);
}
Iterators
Iterator<string> it = Set.iterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
System.out.println ("********************************");
}

Use of generics on map collections (structure: Key--value form)
@Test
public void TestMap () {
map<string, string> map = new hashmap<string, string> ();
Map.put ("www", "111");
Map.put ("QQQ", "222");
Map.put ("TTT", "333");
Traverse the Map collection (there are two ways)
1. Get all keys, get value by key, use the Get method
2. Get the relationship between key and value
Use the first method of traversing
set<string> sets = Map.keyset ();
Iterates over all keys returned by the set
for (String key:sets) {
Get value values for all keys
String value = Map.get (key);
Print output
SYSTEM.OUT.PRINTLN (key + "=" + value);
}

The second way of traversing
The set collection holds the relationship between key and value obtained by the Map.entryset () method
set<entry<string, string>> Set1 = Map.entryset ();
Traversing a collection of relationships
For (entry<string, string> entry:set1) {
Gets the key value in the relationship
String S1 = Entry.getkey ();
Get value values in a relationship
String s2 = Entry.getvalue ();
System.out.println (s1+ "=" +s2);
}

}

The use of generics on the list collection
@Test
public void Testlist () {
list<string> list = new arraylist<string> ();
List.add ("AAAA");
List.add ("bbbb");
List.add
Traversing the list collection
Normal for loop, iterator, enhanced for loop (three ways)
for (int i = 0; i < list.size (); i++) {
String s = list.get (i);
System.out.println (s);
}
System.out.println ("===========================");
Enhanced for Loop
for (String s1:list) {
System.out.println (S1);
}
System.out.println ("===========================");
Iterating through a collection using iterators
Iterator<string> it = List.iterator ();
while (It.hasnext ()) {
System.out.println (It.next ());
}
System.out.println ("********************************");
}
}


Operation Result:



qqq=>222
ttt=>333
www=>111
qqq=>222
ttt=>333
www=>111
Aaaa
bbbb
===========================
Aaaa
bbbb
********************************
Xinxin
Xuanxuan
Baojuan
Xinxin
Xuanxuan
Baojuan
********************************



Application examples of generics in Java


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.