Why use a collection framework
If you don't know how many objects your program will need to run, or if you need to store them in a more complex way, you can use the Java Collection Framework
The Java Collection Framework provides a set of high-performance, easy-to-use interfaces and classes in the java.util package
List interface
Implementation Class of List Interface
ArrayList implements variable-length arrays, allocates continuous space in memory, and traverses elements and accesses elements randomly more efficiently
LinkedList is stored in a chain table, so it is more efficient to insert and delete elements.
ArrayList Collection Class
Determine storage
The ArrayList class is a concrete implementation class of the List interface
ArrayList objects implement variable-size arrays
* It provides better performance when accessing and traversing elements randomly
Determine Storage Objects
Create Type: News Title
Include attributes: ID, name, Creator
Common ArrayList methods
Method Name | Explain |
boolean add(Object o) | Add elements in the order at the end of the list, starting at 0 |
void add(int index,Object o) | Adds an element at the specified index position. The index position must be between 0 and the number of elements in the list |
int size() | Returns the number of elements in the list |
Object get(int index) | Returns the element at the specified index position. The extracted element is of Object type and needs to be cast before use |
boolean contains(Object o) | Determines whether a specified element exists in the list |
boolean remove(Object o) | Remove elements from list |
Object remove(int index) | Deletes the specified location element from the list, starting with 0 for the index position |
package demo01; public class NewsTitle { private int id; private String name; private String author; public NewsTitle() { super(); } public NewsTitle(int id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "NewsTitle [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
package demo01; import java.util.ArrayList; import java.util.Iterator; public class ArrayListDemo01 { public static void main(String[] args) { // Prepare data: Create five NewsTitle class objects NewsTitle nt1 = new NewsTitle(1001, "Sanya Adds Local 480+774", "Baidu"); NewsTitle nt2 = new NewsTitle(1002, "China successfully launched 16 stars with one arrow", "Chinese Space"); NewsTitle nt3 = new NewsTitle(1003, "A companion in distress after a man rescued five people from the water tells the story", "Folk Observation"); NewsTitle nt4 = new NewsTitle(1004, "Su's Ancestor Temple: Su Bingtian is the 29th generation of Su Dongpo", "Life Observation"); NewsTitle nt5 = new NewsTitle(1005, "Parents spend 2 million dollars on baby set ottmannka", "Observation of Hefei"); //Prepare containers: create collection objects, create ArrayList objects ArrayList al = new ArrayList(); //Store data in a collection and add elements to it not by assigning values through element subscripts, but by calling methods on collection objects al.add(nt1); al.add(nt3); al.add(nt4); al.add(nt2); al.add(nt4); //Implement operations on collection elements by calling methods on collection objects //Gets the number of collection elements int size = al.size(); System.out.println("al The number of elements in the collection is:"+size); //Gets the element at the specified location in the collection // Object object0 = al.get(0); // NewsTitle nwt0 = (NewsTitle) object0; // System.out.println(nwt0); // // Object object1 = al.get(1); // NewsTitle nwt1 = (NewsTitle) object1; // System.out.println(nwt1); // // Object object2 = al.get(2); // NewsTitle nwt2= (NewsTitle) object2; // System.out.println(nwt2); // // Object object3 = al.get(3); // NewsTitle nwt3 = (NewsTitle) object3; // System.out.println(nwt3); // // Object object4 = al.get(4); // NewsTitle nwt4 = (NewsTitle) object4; // System.out.println(nwt4); //Traverse Set for (int i = 0; i < al.size(); i++) { Object object = al.get(i); NewsTitle ntw = (NewsTitle)object; System.out.println(ntw); } System.out.println("-------------------"); //Enhanced for Loop Traversal Collection for (Object object : al) { NewsTitle ntw = (NewsTitle)object; System.out.println(ntw); } System.out.println("--------------"); //Traversing a set using an iterator Iterator it=al.iterator(); while(it.hasNext()){ Object object = it.next(); NewsTitle ntw = (NewsTitle)object; System.out.println(ntw); } System.out.println("----------------------"); //Store data in a specified location in a collection al.add(1,nt5); //Enhanced for Loop Traversal Collection for (Object object : al) { NewsTitle ntw = (NewsTitle)object; System.out.println(ntw); } System.out.println("---------------------"); //Delete an element from a collection Object ob = al.remove(1); al.remove(nt3); for (Object object : al) { NewsTitle ntw = (NewsTitle)object; System.out.println(ntw); } //Determines whether a collection contains a specified element boolean result =al.contains(nt1); System.out.println("Include in collection nt3 Elements:"+result); //Determine if the set is empty System.out.println("The collection is empty:"+al.isEmpty()); System.out.println("*************************"); //Convert Collection to Array Object[] objects =al.toArray(); for (int i = 0; i < objects.length; i++) { System.out.println(objects[i]); } System.out.println("********************"); //Empty Collection al.clear(); System.out.println("The collection is empty:"+al.isEmpty()); System.out.println(al.size()); } }
Traversing a set using an iterator
Get the iterator() method of the Iterator:Collection interface
The Iterator method
boolean hasNext(): Determine if another accessible element exists
Object next(): Return the next element to access
Steps:
Collection objects call the iterator() method to take out all elements in the collection in order and place them in the iteration container;
The hasNext() method is then called by the iterator object to determine if there is an element in the iterator, and the element is taken out by the next() method if there is one.
Judging one takes one out, judging one takes one out, so you can use loops to remove all the elements inside.
LinkedList Collection Class
Determine storage
The LinkedList class is a concrete implementation class of the List interface
The LinkedList class is used to create a linked list data structure
* It provides better performance when inserting or deleting elements
LinkedList Common Methods
Method Name | Explain |
void addFirst(Object o) | Add an element at the top of the list |
void addLast(Object o) | Add an element at the end of the list |
Object getFirst() | Returns the first element in the list |
Object getLast() | Returns the last element in the list |
Object removeFirst() | Delete and return the first element in the list |
Object removeLast() | Delete and return the last element in the list |
package demo01; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class LInkedListDemo01 { public static void main(String[] args) { // Prepare data: Create five NewsTitle class objects NewsTitle nt1 = new NewsTitle(1001, "Sanya Adds Local 480+774", "Baidu"); NewsTitle nt2 = new NewsTitle(1002, "China successfully launched 16 stars with one arrow", "Chinese Space"); NewsTitle nt3 = new NewsTitle(1003, "A companion in distress after a man rescued five people from the water tells the story", "Folk Observation"); NewsTitle nt4 = new NewsTitle(1004, "Su's Ancestor Temple: Su Bingtian is the 29th generation of Su Dongpo", "Life Observation"); NewsTitle nt5 = new NewsTitle(1005, "Parents spend 2 million dollars on baby set ottmannka", "Observation of Hefei"); //Prepare container: create collection object, create LinkedList object //List is an interface and LinkedList is the implementation class of the List interface, pointing the List interface reference to an instance of the implementation class //Transition up: References to parent classes (interfaces) point to instances of subclasses, which cannot invoke subclass-specific methods List list = new LinkedList(); list.add(nt1); list.add(nt3); list.add(nt2); list.add(nt2); System.out.println(list.size()); //Traversing a list set using an iterator Iterator it = list.iterator(); while(it.hasNext()){ Object object =it.next(); NewsTitle nt = (NewsTitle)object; System.out.println(nt); } System.out.println("---------------------------"); //Downward transition: Subclass references to parent objects require downward transition because //Parent references cannot invoke methods specific to subclasses, and methods specific to subclasses can only be invoked through subclass objects LinkedList link = (LinkedList) list; link.addFirst(nt5); link.addLast(nt4); for (Object object : link) { System.out.println(object); } System.out.println("-----------------------"); //Gets the first and last element in the collection System.out.println(link.getFirst()); System.out.println(link.getLast()); System.out.println("--------------------------"); //Delete the first and last element in the collection link.removeFirst(); link.removeLast(); for (Object object : link) { System.out.println(object); } } }
Set interface
Set interface stores a unique set of unordered objects HashSet is a reference to the object stored in the implementation class Set commonly used by Set interface.
HashSet is a common implementation class for Set interfaces
case
package demo02; public class NewsTitle { private int id; private String name; private String author; public NewsTitle() { super(); } public NewsTitle(int id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "NewsTitle [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
package demo02; import java.util.HashSet; import java.util.Set; public class HashSetDemo01 { public static void main(String[] args) { //Prepare container: Create HashSet object Set set = new HashSet(); //Preparing data String s1 = new String("java"); String s2 =s1; String s3 = new String("JAVA"); //Add elements to the collection set.add(s1); set.add(s2); set.add(s3); //Gets the number of elements in the collection System.out.println(set.size());//2 } }
package demo02; import java.util.HashSet; import java.util.Set; public class HashSetDemo02 { //Elemental Features of Set Sets: Unique, Unordered public static void main(String[] args) { //Prepare container: Create HashSet object Set set = new HashSet(); //Preparing data String s1 =new String("java"); String s2 = s1; String s3 =new String("java"); set.add(s1); set.add(s2); set.add(s3); System.out.println(set.size());//1 } }
package demo02; import java.util.HashSet; import java.util.Iterator; public class HashSetDemo03 { public static void main(String[] args) { //Prepare containers HashSet hs = new HashSet(); // Prepare data: Create five NewsTitle class objects NewsTitle nt1 = new NewsTitle(1001, "Sanya Adds Local 480+774", "Baidu"); NewsTitle nt2 = new NewsTitle(1002, "China successfully launched 16 stars with one arrow", "Chinese Space"); NewsTitle nt3 = new NewsTitle(1003, "A companion in distress after a man rescued five people from the water tells the story", "Folk Observation"); NewsTitle nt4 = new NewsTitle(1004, "Su's Ancestor Temple: Su Bingtian is the 29th generation of Su Dongpo", "Life Observation"); NewsTitle nt5 = new NewsTitle(1005, "Parents spend 2 million dollars on baby set ottmannka", "Observation of Hefei"); //Store data in a collection hs.add(nt1); hs.add(nt3); hs.add(nt5); hs.add(nt2); hs.add(nt4); hs.add(nt4); //Gets the number of elements in the collection System.out.println(hs.size());//Elements in a set of 5 set s are unique //Get the elements in the collection for (Object object : hs) { NewsTitle nt = (NewsTitle)object; System.out.println(nt); } System.out.println("-------------------"); Iterator it = hs.iterator(); while(it.hasNext()){ Object object =it.next(); NewsTitle nt = (NewsTitle)object; System.out.println(nt); } } }