当前位置:网站首页>Day18 (set, generic, hash table, tree, stack and queue, graph, array and linked list)
Day18 (set, generic, hash table, tree, stack and queue, graph, array and linked list)
2022-06-25 05:38:00 【Liuhaohao yyds】
One 、ArrayListDemo1
package com.shujia.lhw.day18;
import java.util.ArrayList;
import java.util.Iterator;
/*
demand : Use ArrayList Store the string and traverse ( If the string has duplicates, it needs to be removed )
*/
public class ArrayListDemo1 {
public static void main(String[] args) {
// Create a collection object
ArrayList list = new ArrayList();
// Add string elements to the collection
list.add("hello");
list.add("world");
list.add("java");
list.add("hadoop");
list.add("hive");
list.add("hello");
list.add("spark");
list.add("java");
list.add("world");
System.out.println(" The set before de duplication is :"+list);
// Create a new collection to save the de duplicated elements
ArrayList list2 = new ArrayList();
// Traverse the old collection
Iterator iterator = list.iterator();
while(iterator.hasNext()){
String s = (String) iterator.next();
// After getting the element , Take this element to find in the letter collection , If you find a duplicate description, do not add , Otherwise, add to the new set
if(!list2.contains(s)){
list2.add(s);
}
}
System.out.println(" The set after weight removal is :"+list2);
}
}---------------------------------------------------------------------------------------------------------------------------------
Two 、
package com.shujia.lhw.day18;
import java.util.ArrayList;
import java.util.Iterator;
/*
Use ArrayList Store custom objects and traverse ( And remove the weight )
Student object : When the name and age are the same , It means the same person
We follow the logic of handling string repetition to handle custom object repetition , It was found that there was no de duplication , Why? ?
Want to know why , You need to know which line of code the problem is in
After brief answer analysis, it is found that , The problem arises in the line of code that determines whether it is included
Because only when if Statement for true When , Will be added to the new collection
Explain that we judge here , Always for true Of , In other words, contains This method did not work
Find out why it doesn't work , You have to find out contains How does the bottom layer of this method do
contains The underlying method calls equals Method , But what? ,Student Class does not override equals Method
So the call is Object Class equals Method , and Object Class equals Method compares the address value , The students are all new Coming out
The address values must be different ,equals The result of comparison is always false, Plus... In our code ! The result will always be true, So it can be added to anyway
In new collection , The final result is no weight loss .
resolvent :
Element class overrides equals Method , Automatically generated
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// Create a collection object
ArrayList list = new ArrayList();
// Create student objects
Student s1 = new Student(" Wang yu ",18);
Student s2 = new Student(" Ming Wang ",17);
Student s3 = new Student(" Zhou Jiaxiang ",16);
Student s4 = new Student(" Zhang Baogui ",20);
Student s5 = new Student(" Wang yu ",18);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
System.out.println(list);
System.out.println("=======================================");
// Create a new collection to store the results after de duplication
ArrayList list2 = new ArrayList();
// Traverse the old collection
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Student student = (Student) iterator.next();
if(!list2.contains(student)){
list2.add(student);
}
}
System.out.println(list2);
}
}
-------------------------------------------------------------------------------------------------------------------------------
3、 ... and 、 Generic
package com.shujia.lhw.day18;
import java.util.ArrayList;
import java.util.Iterator;
/*
ClassCastException: Type conversion exception
We write it in the normal way , Add some data of different data types to the collection , During traversal, the downward transition is performed , Something went wrong
Why? ?
Because when we store data , Not only does it store string type data , Also stores the Integer type ,Double type ,Student type
The data of
But what? , When we're traversing , Convert the obtained elements into string data , When making wall tiles in the future, you won't report mistakes
Think about the array we learned before , At the time of definition, an array can only store data of the same data type
String[] arr = new String[3];
arr[0] = "0";
// arr[1] = new Student();
If java Collections in mimic data , It is also higher than the practice of restricting data types , When creating a collection, it is good to explicitly store a type of data type
In this way, no exceptions will occur during the subsequent downward transformation
Technology like this ,Java Provides a thing called : Generic
Generic :
Put the work of defining data types , Advance to compile time , Specify the data type of the storage element when creating the collection
This is a bit like passing a data type as a parameter , So generics have another name : Parameterized types
Generic statement definition format :
< Reference data type >
Be careful : Data types in angle brackets can only be reference data types
The benefits of generics :
1、 The problems occurred during our operation , Advance to compile time
2、 There is no need to cast
3、 Optimized the code . Eliminates unnecessary yellow warning lines , Make the code look more concise
Through observation API Find out , Generics can appear in classes , Interface , On the way , What we see is similar to <E> These are called generics , Generally speaking , Generic occurrence
Mostly used in collections
*/
public class GenericDemo {
public static void main(String[] args) {
// Create a List A collection of objects
// stay JDK1.7 after , Generics do automatic type inference
ArrayList<String> list = new ArrayList<>();
// Add elements to the collection
list.add("hello");
list.add("hello");
list.add("hello");
list.add("hello");
list.add("hello");
// list.add("20");
// list.add("12.34");
// list.add(new Student());
// Traverse
// Iterator iterator = list.iterator();
// while(iterator.hasNext()){
// Object next = iterator.next();
//
// String s = (String) next;
//
// System.out.println(next);
//
// }
// Traverse
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String next = iterator.next();
System.out.println(next);
}
}
}
-----------------------------------------------------------------------------------------------------------------------------
Four 、LinkedList
package com.shujia.lhw.day18;
import java.util.LinkedList;
/*
LinkedList:
1、 The underlying data structure is a double linked list , Slow query , Additions and deletions quickly
2、 Threads are not safe , Efficient
LinkedList Proprietary approach :
1、 Add functionality :
public void addFirst(Object e) Add an element at the beginning of the collection
addLast(Object e) Add the last element to the combination , Equate to add() Method
2、 Acquisition function :
public Object getFirst() Gets the first element in the collection
getLast() Get the last element in the collection
3、 Delete function :
public Object removeFirst() Removes the first element from the collection and returns
public Object removeLast() Removes the last element from the collection and returns
*/
public class LinkedListDemo1 {
public static void main(String[] args) {
//1、 establish LinkedList A collection of objects
LinkedList linkedList = new LinkedList();
//2、 Add elements to the collection
linkedList.add("hello");
linkedList.add("world");
linkedList.add("java");
linkedList.add("bigdata");
linkedList.add("hadoop");
linkedList.add("hive");
System.out.println(linkedList);
System.out.println("===================================");
//public void addFirst(Object e) Add an element at the beginning of the collection
linkedList.addFirst("spark");
System.out.println(linkedList);
//addLast(Object e) Add elements at the end of the set , Equate to add() Method
linkedList.addLast("Flink");
//linkedList.add("Flink");
System.out.println(linkedList);
//public Object getFirst() Gets the first element in the collection
Object first = linkedList.getFirst();
System.out.println(first);
System.out.println(linkedList);
//public Object getLast() Get the last element in the collection
Object last = linkedList.getLast();
System.out.println(last);
System.out.println(linkedList);
//public Object removeFirst() Removes the first element from the collection and returns
Object o = linkedList.removeFirst();
System.out.println(o);
System.out.println(linkedList);
//public Object removeLast() Removes the last element from the collection and returns
Object o1 = linkedList.removeLast();
System.out.println(o1);
System.out.println(linkedList);
}
}
---------------------------------------------------------------------------------------------------------------------------
5、 ... and 、LinedListTest
package com.shujia.lhw.day18;
import java.util.Iterator;
import java.util.LinkedList;
/*
Please use LinkedList Set merging test of analog stack data structure
The characteristics of the stack :
fifo
The real meaning of the title is , Write a collection class by yourself , The bottom is LinkedList, Call the method defined by yourself to implement the stack data structure
*/
public class LinkedListTest1 {
public static void main(String[] args) {
// Create a collection object
LinkedList linkedList = new LinkedList();
// linkedList.add("hello");
// linkedList.add("world");
// linkedList.add("java");
linkedList.addFirst("hello");
linkedList.addFirst("world");
linkedList.addFirst("java");
// Traverse
Iterator iterator = linkedList.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
// If at the time of the interview , Encounter such a problem
// Follow these steps , Not a penny
}
}
--------------------------------------------------------------------------------------------------------------------------
6、 ... and 、MyStack
package com.shujia.lhw.day18;
import java.util.LinkedList;
public class MyStack {
private LinkedList linkedList;
MyStack(){
linkedList = new LinkedList();
}
public void myAdd(Object obj){
linkedList.addFirst(obj);
}
public Object myGet(){
// return linkedList.getFirst();
return linkedList.removeFirst();
}
public boolean myIsEmpty(){
return linkedList.isEmpty();
}
}
------------------------------------------------------------------------------------------------------------------------
7、 ... and 、MyStackTest
package com.shujia.lhw.day18;
public class MyStackTest1 {
public static void main(String[] args) {
// Create your own defined collection class
MyStack myStack = new MyStack();
// Add elements to the collection
myStack.myAdd("hello");
myStack.myAdd("world");
myStack.myAdd("java");
myStack.myAdd("bigdata");
System.out.println(myStack.myGet());
System.out.println(myStack.myGet());
System.out.println(myStack.myGet());
System.out.println(myStack.myGet());
// System.out.println(myStack.myGet());//NoSuchElementException
// You should determine whether there are any elements in the collection before getting the elements
while (!myStack.myIsEmpty()){
Object o = myStack.myGet();
System.out.println(o);
}
}
}
------------------------------------------------------------------------------------------------------------------------------
8、 ... and 、Student
package com.shujia.lhw.day18;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
----------------------------------------------------------------------------------------------------------------------------
Nine 、VectorDemo
package com.shujia.lhw.day18;
import java.util.Enumeration;
import java.util.Vector;
/*
Vector:
The underlying data structure is an array , Quick query , Add or delete slowly
Thread safety , Low efficiency ( Although it is thread safe , We will not use it in the future , A thread safe class will replace it later )
Vector Proprietary approach :
public void addElement(Object obj)
Add an element to the end of the collection , And... In effect add() equally
public Object elementAt(int index)
Gets the element at the specified index ,get(int index)
public Enumeration elements()
Returns an enumeration of the components of this vector
*/
public class VectorDemo {
public static void main(String[] args) {
// establish Vector A collection of objects
Vector vector = new Vector();
// Add elements to the collection
vector.addElement("hello");
vector.addElement("java");
vector.add("world");
vector.addElement("java");
// System.out.println(vector);
//public Object elementAt(int index) Gets the element at the specified index get(int index)
Object o = vector.elementAt(0);
System.out.println(o);
System.out.println(vector.elementAt(1));
System.out.println(vector.elementAt(2));
System.out.println(vector.elementAt(3));
// System.out.println(vector.elementAt(4));
System.out.println(vector.get(3));
System.out.println("=================================");
//public Enumeration elements() Returns an enumeration of the elements of this vector
// Simple memory , You see this object as an iterator
Enumeration elements = vector.elements();
while (elements.hasMoreElements()){
Object o1 = elements.nextElement();
String s = (String) o1;
System.out.println(s);
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Ten 、 Hashtable

-------------------------------------------------------------------------------------------------------------------------------
11、 ... and 、 Trees

--------------------------------------------------------------------------------------------------------------------------------
Twelve 、 Arrays and linked lists

-------------------------------------------------------------------------------------------------------------------------------
13、 ... and 、 chart
---------------------------------------------------------------------------------------------------------------------------
fourteen 、 Stacks and queues

边栏推荐
- Design of IM login server and message server
- Even if you are not good at anything, you are growing a little bit [to your 2021 summary]
- C style string
- Electric store stores data
- How to add an external header file in vs?
- [QT] for multithreaded programs, do not use the printf() function to print out
- Dynamic programming example 2 leetcode62 unique paths
- 1.5.3 use tcpdump to observe ARP communication process
- Conflict between v-mode and v-decorator in Ant Design
- A method of automatic continuation of previous tables in word table
猜你喜欢

"APEC industry +" biov Tech talks about the cross-border of Chinese biotechnology enterprises and "Pratt & Whitney Kangyu" | apec-hub public welfare

Dynamic programming example 1 leetcode 322 coin change

Dynamic programming example 2 leetcode62 unique paths

渗透测试-提权专题
![Bind simulation, key points of interpreting bind handwritten code [details]](/img/03/6aa300bb8b8342199aed5a819f3634.jpg)
Bind simulation, key points of interpreting bind handwritten code [details]
![[day40 literature extensive reading] space and time in the child's mind: metallic or atomic](/img/98/10b3e63c9609990c51b619d9ca6179.jpg)
[day40 literature extensive reading] space and time in the child's mind: metallic or atomic

Deep analysis of recursion in quick sorting

Deep learning non local neural networks

Prototypical Networks for Few-shot Learning

Get the first letter of Chinese phonetic alphabet in Excel and capitalize it
随机推荐
Instant messaging project (I)
JSON Library Tutorial from scratch (II): parsing digital learning and sorting notes
Create dynamic array
Detailed summary of position positioning
Svg code snippet of loading animation
Mobile number regular expression input box loses focus verification
Conflict between v-mode and v-decorator in Ant Design
Semantic segmentation cvpr2020 unsupervised intra domain adaptation for semantic segmentation through self supervision
Small sample learning data set
[pan Wai 1] Huawei computer test
电子协会 C语言 1级 28 、字符菱形
Guava-IO
Go implements LRU cache
Creation and use of MySQL index
Keyboard key code value
Classic usage of the sumproduct function
Create an environment for new projects
On Transform
The article is on the list. Welcome to learn
Handwritten promise all