Article directory
Collections in Java
- concept
- Architecture
- practical application
concept
Collection in Java is a tool class that can store any number of objects with common properties.
Compare arrays? Why use collections?
Problem solved by array: store 20 students' information. 20 fixed length
Collection solves the problem of storing product information. Indefinite quantity
The set is applicable to the scene of dynamic change of data length
- Indefinite quantity
- One to one relationship
- Need to add or delete data
- Data duplication
Architecture
- Collection
- Map
Collection: object of storage class
Map: storing information as key value pairs
Interface provided by Collection
- List sequence is ordered and repeatable - > ArrayList
- Queue queue order repeatable - > LinkedList
- Set set is out of order and not repeated - > HashSet
Map -> HashMap
List
- A repeatable set of interfaces to a set, called a sequence
- You can precisely control the insertion position of each element, or delete elements in a certain position
- Implementation class ArrayList LinkedList
ArrayList stores an array like LinkedList is actually a linked list
ArrayList
It is a data with dynamic growth in length. It is the most efficient to insert and delete data at the end of the list,
More suitable for finding and updating elements, elements in ArrayList can be Null
- Store string information in ArrayList
package com.dd1; import java.util.ArrayList; import java.util.List; public class Demo1 { public static void main(String[] args) { // Output string using ArrayList List alist = new ArrayList(); // Open up a continuous memory space alist.add("Java"); // Add java to the space of idx 0 alist.add("C"); // ... alist.add("C++"); alist.add("Python"); System.out.println("The number of elements in the list is:" + alist.size()); // Traversal output all changes to Prolog System.out.println("*****************"); for (int i = 0; i < alist.size(); i++) { System.out.println(alist.get(i)); } System.out.println("remove idx1"); // alist.remove(1); alist.remove("C"); for (int i = 0; i < alist.size(); i++) { System.out.println(alist.get(i)); } } }
Add custom class content in ArrayList
- Announcement management
- Add and display
- Insert at specified location
- delete
- modify
Notice category:
- number
- Title
- Founder
- Creation time
- Construction method
- get method of member property
- set method of member property
// Custom Notice class package com.dd1; import java.util.Date; public class Notice { private int id; private String title; private String creator; private Date createTime; public Notice(int id, String title, String creator, Date createTime) { this.id = id; this.title = title; this.creator = creator; this.createTime = createTime; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
// Main method implementation package com.dd1; import java.util.ArrayList; import java.util.Date; public class NoticeTest { public static void main(String[] args) { // create object Notice nt1 = new Notice(1, "Title1", "Admin", new Date()); Notice nt2 = new Notice(2, "Title2", "Admin", new Date()); Notice nt3 = new Notice(3, "Title3", "Admin", new Date()); // Add announcement ArrayList ntList = new ArrayList(); ntList.add(nt1); ntList.add(nt2); ntList.add(nt3); // Display announcement System.out.println("The contents of the announcement are:"); for (int i = 0; i < ntList.size(); i++) { Notice nt = (Notice) ntList.get(i); System.out.println(i + 1 + ":" + nt.getTitle()); } // Add announcement Notice nt4 = new Notice(4, "Title4", "Admin", new Date()); // Add after first announcement ntList.add(1, nt4); System.out.println("The contents of the announcement are:"); for (int i = 0; i < ntList.size(); i++) { Notice nt = (Notice) ntList.get(i); System.out.println(i + 1 + ":" + nt.getTitle()); } // Delete announcement // ntList.remove(0); // ntList.remove(nt4); // System.out.println("content of announcement is:"); // for (int i = 0; i < ntList.size(); i++) { // Notice nt = (Notice) ntList.get(i); // System.out.println(i + 1 + ":" + nt.getTitle()); // } // Modify bulletin nt4 nt4.setTitle("setTitle4"); ntList.set(1, nt4); System.out.println("The contents of the announcement are:"); for (int i = 0; i < ntList.size(); i++) { Notice nt = (Notice) ntList.get(i); System.out.println(i + 1 + ":" + nt.getTitle()); } } }
Set
A set of elements that do not need and cannot be repeated is called a set
- HashSet
- disorder
- A null is allowed without repetition
- Good access and search performance
There is no get method of ArrayList in the Set to retrieve the elements in the Set. The Iterator is used
- Iterator interface can traverse various collection elements in a unified way
- The hasNext() method detects if there is another element in the collection
- The next() method returns the next element in the collection
Simple use
package com.dd2; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class WordDemo { public static void main(String[] args) { // Store English words in HashSet Set st = new HashSet(); st.add("blue"); st.add("black"); st.add("yellow"); st.add("white"); // output System.out.println("The elements in the collection are:"); Iterator its = st.iterator(); // Iterate through the iterator and output elements while (its.hasNext()) { System.out.print(its.next() + "--"); } // Insert a new word into the collection. There is no index method because it is unordered st.add("Red"); // The program will not insert duplicate data into the collection st.add("white"); its = st.iterator(); // Iterate through the iterator and output elements System.out.println("insert Red Output results after"); while (its.hasNext()) { System.out.print(its.next() + "--"); } } }
Pet cat information management
Demand:
- Add and display pet cat information
- Find the information of a pet cat and output
- Modify pet information
- Delete pet information
Cat
package com.dd2; import java.util.Objects; public class Cat { private String name; private Integer month; private String species; public Cat(String name, Integer month, String species) { this.name = name; this.month = month; this.species = species; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getMonth() { return month; } public void setMonth(Integer month) { this.month = month; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", month=" + month + ", species='" + species + '\'' + '}'; } @Override public boolean equals(Object o) { // Object equal true if (this == o) return true; // Judge whether it is an object if (!(o instanceof Cat)) return false; Cat cat = (Cat) o; return Objects.equals(getName(), cat.getName()) && Objects.equals(getMonth(), cat.getMonth()) && Objects.equals(getSpecies(), cat.getSpecies()); } @Override public int hashCode() { return Objects.hash(getName(), getMonth(), getSpecies()); } }
Main method
package com.dd2; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class CatTest { public static void main(String[] args) { Cat hh = new Cat("hh", 12, "hh1"); Cat ff = new Cat("ff", 12, "ff1"); Set<Cat> st = new HashSet(); st.add(hh); st.add(ff); Iterator<Cat> its = st.iterator(); while (its.hasNext()) { System.out.println(its.next()); } // When adding objects with the same properties but different addresses to Set, the equals method should be considered Cat hh1 = new Cat("hh", 12, "hh1"); st.add(hh1); its = st.iterator(); System.out.println("-------"); while (its.hasNext()) { System.out.println(its.next()); } // find information Cat hh2 = new Cat("Huahua 2", 2, "hh2"); st.add(hh2); System.out.println("Add to hh2 Post cat information"); its = st.iterator(); while (its.hasNext()) { System.out.println(its.next()); } // if (st.contains(hh2)) { System.out.println("existence hh2"); } else { System.out.println("Non-existent hh"); } // Find by attribute boolean flag = false; Cat c = null; its = st.iterator(); while (its.hasNext()) { c = its.next(); if (c.getName().equals("Huahua 2")) { flag = true; break; } } if (flag) { System.out.println("Find Huahua 2"); System.out.println(c); } else { System.out.println("No flower 2 found"); } // Delete traversal - > condition remove for (Cat ct : st) { if (ct.getName().equals("Huahua 2")) { st.remove(ct); System.out.println("Execution deletion"); } } for (Cat ct : st) { System.out.println(ct); } // Remove all removeAll st.isempty() methods to determine if the collection is empty } }
Map
- Store data in the form of key value in Map
- Key value exists as an object instance of type Entry
- You can quickly find the value through key
- key cannot be duplicate, only one value can be mapped
HashMap
- Implementation of Map interface based on hash table
- Allow null values and null keys
- Entry objects are unordered in a HashMap
Commodity information
- id
- name
- price
Method
- structure
- set get
- toString
Good
package com.dd3; public class Goods { private String id; private String name; private double price; public Goods(String id, String name, double price) { this.id = id; this.name = name; this.price = price; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", price=" + price + '}'; } }
Main method
package com.dd3; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class GoodsTest { public static void main(String[] args) { Scanner console = new Scanner(System.in); // Defining a HashMap object Map<String, Goods> gm = new HashMap<String, Goods>(); // Importation of goods System.out.println("Enter product:"); int i = 0; while (i < 3) { System.out.println("Input No." + (i + 1) + "Article commodity"); System.out.println("Serial number:"); String nb = console.next(); // Judge whether there is duplication if (gm.containsKey(nb)) { System.out.println("Duplicate item number"); continue; } System.out.println("Trade name:"); String gn = console.next(); System.out.println("Price:"); double pr = 0; try { pr = console.nextDouble(); } catch (java.util.InputMismatchException e) { System.out.println("Price must be numeric"); // Collect the wrong next, otherwise the wrong next will be brought to the next loop console.next(); continue; } Goods g = new Goods(nb, gn, pr); // Add product information to Map gm.put(nb, g); i++; } // Traversing Map for (Goods g : gm.values()) { System.out.println(g); } } }