Collections in Java
A collection is like a shopping cart that stores all purchased goods in a single shopping cart
The concept of sets
-
Real life: many things come together
-
Sets in Mathematics: The Overall of Things with Common Attributes
-
Collection class in Java: is a tool class, a container that can store any number of classes with the same properties.
The role of sets
-
Organizing data within classes
-
Simple and fast search for a large number of entries
-
Some collection excuses provide a series of ordered elements that can be quickly inserted or deleted in a sequence
-
Some collection interfaces provide mapping relationships that allow you to quickly find the corresponding unique object by using a key word, which can be of any type
Two Collection Frames
-
Collection
- List
- Queue
- Set
Differences between List, Queue, Set:
The elements in List and Queue are ordered
The elements in the Set are out of order
graph TD Collection(Collection) --> List(List) List(List) -.-> ArrayList[ArrayList] List(List) -.-> LinkedList[LinkedList] Collection(Collection) --> Queue(Queue) Queue(Queue)-.-> LinkedList[LinkedList] Collection(Collection) --> Set(Set) Set(Set) -.-> HashSet[HashSet] style ArrayList fill:#F4493F,color:#fff style HashSet fill:#F4493F,color:#fff style List fill:#00A9D4,color:#fff style Set fill:#00A9D4,color:#fffStored in Collection is a separate object
-
Map
In Map, data is stored in <Key, Value>, which is a mapping relationship between two objects, a bit like the Diectory type in C#
Collection interface, subinterface and its implementation class
List interface and its implementation class--- ArrayList
- Elements in a List can be repetitive and ordered and are called sequences
- List s can precisely control where each element is inserted or delete a location element
- ArrayList, an array sequence, is an important implementation class of List
- The bottom level of ArrayList is implemented by arrays
Implement Function--Simulate the Students'Course Selection Function
- Select courses (add courses to the collection)
- Delete a selected course (delete elements from the collection)
- View selected courses
- Modify selected courses
//: Course.java package com.faraj.collection; public class Course { public String name; public String id; public Course(String id, String name) { this.id = id; this.name = name; } }
Course.java is a course class. Because it is learning, the attributes in the class are used in the public application. private modification should be used, then getName; setName; getId; SetId method should be added.
//: Student.java package com.faraj.collection; import java.util.HashSet; import java.util.Set; public class Student { public String id; public String name; public Set<Course> courses; public Student(String id, String name){ this.id = id; this.name = name; this.courses = new HashSet<Course>(); } }
Create Student.java
//: ListTest.java package com.faraj.collection; import java.util.*; public class ListTest { public List<Course> coursesToSelect; public ListTest() { this.coursesToSelect = new ArrayList<Course>(); } /** * Add elements to courseToSelect */ public void addTest() { Course cr1 = new Course("1", "Introduction to Database System"); coursesToSelect.add(cr1); Course temp = coursesToSelect.get(0); System.out.println("Course added: " + temp.id + "-" + temp.name); coursesToSelect.add(0, new Course("2", "data structure")); Course temp2 = coursesToSelect.get(0); System.out.println("Course added: " + temp2.id + "-" + temp2.name); coursesToSelect.add(0, new Course("2", "data structure")); Course[] courses = new Course[]{ new Course("3", "linear algebra"), new Course("4", "ASP Web Design") }; coursesToSelect.addAll(Arrays.asList(courses)); System.out.println("Course added: " + coursesToSelect.get(2).id + "-" + coursesToSelect.get(2).name); System.out.println("Course added: " + coursesToSelect.get(3).id + "-" + coursesToSelect.get(3).name); coursesToSelect.addAll(2, Arrays.asList( new Course("5", "object-oriented programming"), new Course("6", "assembly language"))); System.out.println("Course added: " + coursesToSelect.get(2).id + "-" + coursesToSelect.get(2).name); System.out.println("Course added: " + coursesToSelect.get(3).id + "-" + coursesToSelect.get(3).name); } /** * Gets all the elements in the collection */ public void getTest() { for (int i = 0; i < coursesToSelect.size(); i++) { System.out.println("Course:" + coursesToSelect.get(i).id + " - " + coursesToSelect.get(i).name); } } /** * Iterate through a List */ public void iteratorTest() { Iterator<Course> it = coursesToSelect.iterator(); int i = 1; while (it.hasNext()) { Course cr = it.next(); System.out.println("curriculum" + i++ + ": " + cr.id + "-" + cr.name); } } /** * Loop through all elements in the list using foreach */ public void foreachTest() { int i = 1; for (Course cr : coursesToSelect) { System.out.println("curriculum" + i++ + ": " + cr.id + "-" + cr.name); } } /** * Modify elements in a List */ public void modifyTest() { coursesToSelect.set(1, new Course("7", "Java Language Design")); } /** * Delete elements from the List */ public void removeTest(){ coursesToSelect.remove(0); } public static void main(String[] args) { ListTest lt = new ListTest(); lt.addTest(); // lt.getTest(); // lt.iteratorTest(); lt.modifyTest(); lt.removeTest(); lt.foreachTest(); } }
Create alternative course class ListTest.java
package com.faraj.collection; import java.util.*; public class SetTest { public List<Course> coursesToSelect; public SetTest() { coursesToSelect = new ArrayList<Course>(); } public void add() { coursesToSelect.addAll( Arrays.asList( new Course("1", "Introduction to Database System"), new Course("2", "C Language Foundation"), new Course("3", "Python Language Practice"), new Course("4", "Basic algorithm implementation"), new Course("5", "assembly language"), new Course("6", "Linux Basics"), new Course("7", "object-oriented programming")) ); } public void getAll() { for (Course c : coursesToSelect) { System.out.println(c.id + "--" + c.name); } } public static void main(String[] args) { SetTest st = new SetTest(); st.add(); st.getAll(); Student stu = new Student("1", "Faraj"); Scanner sca = new Scanner(System.in); System.out.println("Welcome Stu. " + stu.name + "to select courses. You should and only can select 3 course."); int num = 1; for (int i = 0; i < 3; i++) { System.out.println("Please choose NO. " + num + " course's ID"); num ++; String input = sca.next(); for (Course cor : st.coursesToSelect) { if (cor.id.equals(input)) { stu.courses.add(cor); } } } System.out.println("You chose:"); for (Course stuC : stu.courses) { System.out.println(stuC.id + " - " + stuC.name); } } }
Map and HashMap
Map interface
- Map provides a mapping relationship where elements are stored as key-value () pairs, enabling value lookups based on keys
- Key-value pairs in Map exist as object instances of type Entry
- The key is not repeatable, but the value is repeatable
- Only one value can be mapped per key
- Map Supports Normality, Map<K, V>
HashMap class
- HashMap is an important and most commonly used implementation class of Map, implemented based on hash tables
- Entry objects in HashMap are out of order
- Both Key and Value values can be null, but there can only be one map with a Key value of null in a HashMap (Key values cannot be repeated)
Case:
Function Description: Student Information Management via Map<String
Where key is the student ID and value is the student object
Keyboard input of student information
Addition, deletion, and alteration of student information in the collection
Create MapTest.java
//: MapTest.java package com.faraj.collection; import java.util.*; public class MapTest { public Map<String, Student> students; public MapTest() { students = new HashMap<>(); } /** * Add entry (key-value pair) to Map by put method */ public void putTest() { Scanner scan = new Scanner(System.in); while (true) { System.out.println("Please enter a student ID"); String id = scan.next(); int nextInput; if (students.get(id) == null) { System.out.println("Please enter the student's name"); students.put(id, new Student(id, scan.next())); System.out.println("Do you want to continue adding?1 Continue 2 Exit"); nextInput = scan.nextInt(); if (nextInput != 1) { if (nextInput == 2) break; } } else { System.out.println("this ID Already exists"); System.out.println("Whether to add 1 again or not is 2 exit"); while (true) { try { nextInput = scan.nextInt(); break; } catch (InputMismatchException e) { System.out.println("The content you entered is illegal,Please re-enter"); } } if (nextInput != 1) { if (nextInput == 2) break; } } } } /** * Get traversed students through keySet */ public void keySetTest() { Set<String> keys = students.keySet(); System.out.println("The number of students has now been added:" + keys.size()); for (String stuId : keys) { System.out.println("Student (" + stuId + ")" + students.get(stuId).name); } } /** * Traversing students using entrySet */ public void entrySetTest() { Set<Map.Entry<String, Student>> entries = students.entrySet(); System.out.println("Total number of students:" + entries.size()); for (Map.Entry<String, Student> entry : entries) { System.out.println(entry.getKey() + " - " + entry.getValue().name); } } /** * Delete Students from Map */ public void removeTest() { Scanner scan = new Scanner(System.in); while (true) { System.out.println("Please enter the student you want to delete ID"); String id = scan.next(); if (students.get(id) == null) { System.out.println("The student could not be found ID"); System.out.println("Enter 1 for re-entry and 2 for exit"); int next = scan.nextInt(); if (next != 1) { if (next == 2) { break; } } } else { System.out.println("Student (" + id + ")" + students.get(id).name + " have been deleted"); students.remove(id); System.out.println("Enter 1 for re-entry and 2 for exit"); int next = scan.nextInt(); if (next != 1) { if (next == 2) { break; } } } } } /** * Change student name by Put method */ public void modifyTest() { Scanner scan = new Scanner(System.in); while (true) { System.out.println("Please enter the student's ID"); String stuId = scan.next(); Student stu = students.get(stuId); if (stu == null) { System.out.println("this ID Student does not exist, please re-enter"); continue; } System.out.println("Current Student (" + stuId + ")" + " - " + stu.name + ", Please enter the modified name"); String newName = scan.next(); Student newStu = new Student(stuId,newName); students.put(stuId,newStu); break; } } public static void main(String[] args) { MapTest mt = new MapTest(); mt.putTest(); mt.keySetTest(); mt.modifyTest(); mt.entrySetTest(); } }
Determine if a course exists in coursesToSelect(List)
Override equals method in Course.java
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Course)){ return false; } Course cour = (Course)obj; if (cour.name == null){ return this.name == null; }else{ return this.name.equals(cour.name); } }
Add the following methods to the SetTest.java class
public void containsTest() { System.out.println("Please enter the name you are looking for"); Course inputCourse = new Course(); inputCourse.name = scan.next(); if (coursesToSelect.contains(inputCourse)) System.out.println("Contains" + inputCourse.name + ">"); else System.out.println("Does not contain" + inputCourse.name + ">"); }
Testing this method in the main method of SetTest.java
st.containsTest();
There is also a containsAll() method in the List that is similar in usage to contains, where a collection of compared objects is passed in
Determine if there is a course in the Set
Extract some of the code from the previous SetTest.java into a separate method
public void createStuAndSelectCourse(){ Student stu = new Student("1", "Faraj"); System.out.println("Welcome Stu. " + stu.name + "to select courses. You should and only can select 3 course."); int num = 1; for (int i = 0; i < 3; i++) { System.out.println("Please choose NO. " + num + " course's ID"); num++; String input = scan.next(); for (Course cor : coursesToSelect) { if (cor.id.equals(input)) { stu.courses.add(cor); } } } System.out.println("You chose:"); for (Course stuC : stu.courses) { System.out.println(stuC.id + " - " + stuC.name); } }
Create a method in this file
public void setContainsTest() { System.out.println("Please enter a course name for the student selection"); String name = scan.next(); Course inputCourse = new Course(); inputCourse.name = name; if (student.courses.contains(inputCourse)) { System.out.println("The student chose The" + inputCourse.name + ">"); } else { System.out.println("The student did not choose "" + inputCourse.name + ">"); } }
Call the two newly created methods in the main method
st.createStuAndSelectCourse(); st.setContainsTest();
Running the program found that the contains method in HashSet tells us that there are no courses included
Don't worry, it's not because our code was written incorrectly, it's...
Implementation Mechanism of HashSet contains Method
In addition to the equals() method overridden by the Course class above, the Object root class also defines a **hashCode()** method that returns the value of the object's hash code. When we call the contains() method of the HashSet, it first calls each element's hashCode to get its hash code. If the hash codes are equal, EQ will be calledThe uals method determines equality, which occurs when both methods return true values before the contains() method determines that the HashSet contains an element.
Adding overrides to hashCode methods in Course classes
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }
Then restart the program and you will see that it is working properly