JavaSE Colloection
List
ArrayList
ArrayListDemo1 点击查看代码
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class ArrayListDemo1 {
public static void main(String[] args) {
Collection<String> list = new ArrayList<>();
String[] strings = new String[] { new String("Hello"), new String("World") };
initList(list, strings);
traverseList(list);
}
private static void traverseList(Collection<String> list) {
fun1(list);//迭代器遍历
fun2(list);//for-each循环遍历
fun3(list);//普通for循环遍历
}
private static void fun3(Collection<String> list) {
System.out.print("普通for循环遍历:");
for (int i = 0; i < list.size(); i++) {
System.out.print(((ArrayList<String>) list).get(i) + "\t");
}
System.out.println("\n");
}
private static void fun2(Collection<String> list) {
System.out.print("for-each循环遍历:");
for (String string : list) {
System.out.print(string + "\t");
}
System.out.println("\n");
}
private static void fun1(Collection<String> list) {
//迭代器遍历
System.out.print("迭代器遍历:");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
System.out.print(s + "\t");
}
System.out.println("\n");
}
private static void initList(Collection<String> list, String[] strings) {
for (String str : strings) {
list.add(str);
}
}
}
运行结果
迭代器遍历:Hello World
for-each循环遍历:Hello World
普通for循环遍历:Hello World
ArrayListDemo2 点击查看代码
import java.util.ArrayList;
import java.util.Objects;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
public class ArrayListDemo2 {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student[] students=new Student[]{
new Student("张三", 18, "男"),
new Student("李四", 19, "男"),
new Student("王五", 12, "男"),
new Student("张三", 18, "男")
};
initList(list, students);
traverseList(list);
}
private static void traverseList(ArrayList<Student> list) {
for (Student student : list) {
System.out.println(student+"\n");
}
}
private static void initList(ArrayList<Student> list, Student[] students) {
for (Student student : students) {
list.add(student);
}
}
}
运行结果
{ name='张三', age='18', gender='男'}
{ name='李四', age='19', gender='男'}
{ name='王五', age='12', gender='男'}
{ name='张三', age='18', gender='男'}
LinkedList
LinkedListDemo 点击查看代码
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
String[] strings = new String[] {
new String("刘备"),
new String("关羽"),
new String("张飞"),
new String("赵云"),
new String("黄忠"),
};
initList(list, strings);
traverseList(list);
System.out.println();
list.addFirst("曹操");
System.out.println(list);
System.out.println("====================================\n");
list.addLast("许褚");
System.out.println(list);
System.out.println("====================================\n");
String s1 = list.getFirst();
System.out.println(s1);
System.out.println("====================================\n");
String s2 = list.getLast();
System.out.println(s2);
System.out.println("====================================\n");
String s3 = list.removeFirst();
System.out.println(s3);
System.out.println("====================================\n");
String s4 = list.removeLast();
System.out.println(s4);
System.out.println("====================================\n");
}
private static void traverseList(LinkedList<String> list) {
System.out.print("初始化List后:");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
System.out.print(s + "\t");
}
System.out.println();
}
private static void initList(LinkedList<String> list, String[] strings) {
for (String string : strings) {
list.add(string);
}
System.out.println();
}
}
运行结果
初始化List后:刘备 关羽 张飞 赵云 黄忠
[曹操, 刘备, 关羽, 张飞, 赵云, 黄忠]
====================================
[曹操, 刘备, 关羽, 张飞, 赵云, 黄忠, 许褚]
====================================
曹操
====================================
许褚
====================================
曹操
====================================
许褚
====================================
Set
HashSet
HashSetDemo1 点击查看代码
package Set.HashSet;
import java.util.HashSet;
//练习 : 使用HashSet集合存储字符串并遍历
public class HashSetDemo1 {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
String[] strings = new String[] {
new String("张三"),
new String("李四"),
new String("王五"),
new String("赵六"),
new String("周七"),
new String("张三"),
new String("李四"),
new String("赵六"),
new String("周七"),
new String("张三"),
new String("李四")
};
initSet(set, strings);
traverseSet(set);
}
private static void traverseSet(HashSet<String> set) {
for (String string : set) {
System.out.print(string + "\t ");
}
}
private static void initSet(HashSet<String> set, String[] strings) {
for (String string : strings) {
set.add(string);
}
}
}
运行结果
李四 周七 张三 王五 赵六
HashSetDemo2 点击查看代码
package Set.HashSet;
import java.util.*;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
// 练习 : 使用HashSet集合存储自定义对象并遍历
public class HashSetDemo2 {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<>();
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 19, "男"),
new Student("王五", 12, "男"),
new Student("张三", 18, "男"),
new Student("李四", 19, "男"),
new Student("王五", 12, "男")
};
initList(set, students);
traverseList(set, students);
}
private static void traverseList(HashSet<Student> set, Student[] students) {
Iterator<Student> iterator = set.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student + "\t");
}
}
private static void initList(HashSet<Student> set, Student[] students) {
for (Student student : students) {
set.add(student);
}
}
}
运行结果
{ name='李四', age='19', gender='男'}
{ name='张三', age='18', gender='男'}
{ name='王五', age='12', gender='男'}
LinkedHashSet
LinkedHashSetDemo 点击查看代码
TreeSet
TreeSetDemo1 点击查看代码
package Set.TreeSet;
import java.util.*;
/**
* TreeSet集合特点
*
* 不包含重复元素的集合
* 没有带索引的方法
* 可以将元素按照规则进行排序
*
*/
public class TreeSetDemo1 {
// 存储Integer类型的整数,并遍历
public static void main(String[] args) {
TreeSet<Integer> treeset = new TreeSet<>();
Integer[] integers = new Integer[] { 9, 2, 8, 1, 5, 1 };
initTreeSet(treeset, integers);
traverseTreeSet(treeset);
}
private static void traverseTreeSet(TreeSet<Integer> treeset) {
for (Integer integer : treeset) {
System.out.print(integer + "\t");
}
}
private static void initTreeSet(TreeSet<Integer> treeset, Integer[] integers) {
for (Integer integer : integers) {
treeset.add(integer);
}
}
}
运行结果
1 2 5 8 9
TreeSetDemo2 点击查看代码
package Set.TreeSet;
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
@Override
public int compareTo(Student o) {
return this.age - o.age == 0 ? this.name.compareTo(o.name) : this.age - o.age;
}
// @Override
// public int compareTo(Student o) {
// if (this.age != o.age) {
// return Integer.compare(this.age, o.age);
// } else {
// return this.name.compareTo(o.name);
// }
// }
}
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet<Student> treeset = new TreeSet<>();
Student[] students = new Student[] {
new Student("A张三", 18, "男"),
new Student("S李四", 20, "男"),
new Student("D王五", 18, "女"),
new Student("F赵六", 20, "男"),
new Student("G孙七", 18, "女"),
new Student("H赵六", 20, "男"),
new Student("J孙七", 18, "女")
};
initTreeSet(treeset, students);
traverseTreeSet(treeset);
}
private static void traverseTreeSet(TreeSet<Student> treeset) {
for (Student student : treeset) {
System.out.println(student + "\n");
}
}
private static void initTreeSet(TreeSet<Student> treeset, Student[] students) {
for (Student student : students) {
treeset.add(student);
}
}
}
运行结果
{ name='A张三', age='18', gender='男'}
{ name='D王五', age='18', gender='女'}
{ name='G孙七', age='18', gender='女'}
{ name='J孙七', age='18', gender='女'}
{ name='F赵六', age='20', gender='男'}
{ name='H赵六', age='20', gender='男'}
{ name='S李四', age='20', gender='男'}
TreeSetDemo3 点击查看代码
package Set.TreeSet;
import java.util.*;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
class ComparatorImpl implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge() == 0 ? o1.getName().compareTo(o2.getName()) : o1.getAge() - o2.getAge();
}
}
public class TreeSetDemo3 {
public static void main(String[] args) {
TreeSet<Student> treeset = new TreeSet<>(new ComparatorImpl());
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 20, "男"),
new Student("王五", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女")
};
initTreeSet(treeset, students);
traverseTreeSet(treeset);
}
private static void traverseTreeSet(TreeSet<Student> treeset) {
for (Student student : treeset) {
System.out.println(student + "\n");
}
}
private static void initTreeSet(TreeSet<Student> treeset, Student[] students) {
for (Student student : students) {
treeset.add(student);
}
}
}
运行结果
{ name='孙七', age='18', gender='女'}
{ name='张三', age='18', gender='男'}
{ name='王五', age='18', gender='女'}
{ name='李四', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
TreeSetDemo4 点击查看代码
package Set.TreeSet;
import java.util.*;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
public class TreeSetDemo4 {
public static void main(String[] args) {
TreeSet<Student> treeset = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge() == 0 ? o1.getName().compareTo(o2.getName()) : o1.getAge() - o2.getAge();
}
});
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 20, "男"),
new Student("王五", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女")
};
initTreeSet(treeset, students);
traverseTreeSet(treeset);
}
private static void traverseTreeSet(TreeSet<Student> treeset) {
for (Student student : treeset) {
System.out.println(student + "\n");
}
}
private static void initTreeSet(TreeSet<Student> treeset, Student[] students) {
for (Student student : students) {
treeset.add(student);
}
}
}
运行结果
{ name='孙七', age='18', gender='女'}
{ name='张三', age='18', gender='男'}
{ name='王五', age='18', gender='女'}
{ name='李四', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
Collections
shuffleDemo 点击查看代码
package Collections.shuffle;
import java.util.*;
public class shufleDemo {
public static void main(String[] args) {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Collections.shuffle(Arrays.asList(numbers));
System.out.println(Arrays.toString(numbers));
}
}
运行结果
[2, 7, 8, 6, 4, 1, 5, 3, 9]
Sort
SortDemo1 点击查看代码
package Collections.Sort;
import java.util.*;
public class SortDemo1 {
public static void main(String[] args) {
Integer[] integers = new Integer[] { 9, 2, 8, 1, 5, 1 };
List<Integer> list = new ArrayList<>();
initList(list, integers);
Collections.sort(list);
System.out.println(list);
}
private static void initList(List<Integer> list, Integer[] integers) {
for (Integer integer : integers) {
list.add(integer);
}
}
}
运行结果
[1, 1, 2, 5, 8, 9]
SortDemo2 点击查看代码
package Collections.Sort;
import java.util.*;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
public class SortDemo2 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 20, "男"),
new Student("王五", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女")
};
initList(list, students);
Collections.sort(list,
Comparator.comparing(Student::getAge).thenComparing(Student::getName).thenComparing(Student::getGender));
traverseList(list);
}
private static void traverseList(List<Student> list) {
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student + "\n");
}
}
private static void initList(List<Student> list, Student[] students) {
for (Student student : students) {
list.add(student);
}
}
}
运行结果
{ name='孙七', age='18', gender='女'}
{ name='孙七', age='18', gender='女'}
{ name='张三', age='18', gender='男'}
{ name='王五', age='18', gender='女'}
{ name='李四', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
SortDemo3 点击查看代码
package Collections.Sort;
import java.util.*;
class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
}
public class SortDemo3 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 20, "男"),
new Student("王五", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女")
};
initList(list, students);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge() == 0 ? o1.getName().compareTo(o2.getName()) : o1.getAge() - o2.getAge();
}
});
traverseList(list);
}
private static void traverseList(List<Student> list) {
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student + "\n");
}
}
private static void initList(List<Student> list, Student[] students) {
for (Student student : students) {
list.add(student);
}
}
}
运行结果
{ name='孙七', age='18', gender='女'}
{ name='孙七', age='18', gender='女'}
{ name='张三', age='18', gender='男'}
{ name='王五', age='18', gender='女'}
{ name='李四', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
{ name='赵六', age='20', gender='男'}
SortDemo4 点击查看代码
package Collections.Sort;
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
public Student gender(String gender) {
setGender(gender);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age && Objects.equals(gender, student.gender);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
", gender='" + getGender() + "'" +
"}";
}
@Override
public int compareTo(Student o) {
return this.age - o.getAge() == 0 ? this.name.compareTo(o.getName()) : this.age - o.getAge();
}
}
public class SortDemo4 {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student[] students = new Student[] {
new Student("张三", 18, "男"),
new Student("李四", 20, "男"),
new Student("王五", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女"),
new Student("赵六", 20, "男"),
new Student("孙七", 18, "女")
};
initList(list, students);
traverseList(list);
}
private static void traverseList(List<Student> list) {
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student + "\n");
}
}
private static void initList(List<Student> list, Student[] students) {
for (Student student : students) {
list.add(student);
}
}
}
运行结果
{ name='张三', age='18', gender='男'}
{ name='李四', age='20', gender='男'}
{ name='王五', age='18', gender='女'}
{ name='赵六', age='20', gender='男'}
{ name='孙七', age='18', gender='女'}
{ name='赵六', age='20', gender='男'}
{ name='孙七', age='18', gender='女'}
Search
SearchDemo 点击查看代码
package Search;
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[] array = new int[] { 9, 2, 8, 1, 5, 1, 4, 0, 2, 5, 6, 8 };
System.out.println("原数组:" + Arrays.toString(array));
Arrays.sort(array);
System.out.println("排序后:" + Arrays.toString(array));
int index1 = MyBinarySearch(array, 8);
System.out.println(8 + "在数组中的下标为" + index1);
int index2 = MyBinarySearch(array, 985);
System.out.println(index2);
}
private static int MyBinarySearch(int[] array, int targetNum) {
int min = 0;
int max = array.length - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (array[mid] > targetNum) {
max = mid - 1;
}
if (array[mid] < targetNum) {
min = mid + 1;
}
if (array[mid] == targetNum) {
return mid;
}
}
return -1;
}
}
运行结果
原数组:[9, 2, 8, 1, 5, 1, 4, 0, 2, 5, 6, 8]
排序后:[0, 1, 1, 2, 2, 4, 5, 5, 6, 8, 8, 9]
8在数组中的下标为10
-1
Map
HashMap
HashMapDemo1 点击查看代码
package Map.HashMap;
import java.util.*;
public class HashMapDemo1 {
/*
* 底层结构是哈希表结构,具有键唯一,无序,特点
*/
// 键不能重复,值可以重复
public static void main(String[] args) {
HashMap<String, String> hashmap = new HashMap<>();
hashmap.put("319102020330", "李华");
hashmap.put("319102020331", "张三");
hashmap.put("319102020332", "李四");
hashmap.put("319102020333", "王五");
hashmap.put("319102020330", "政然");
hashmap.put("319102020331", "张三");
System.out.println(hashmap);
}
}
运行结果
{319102020333=王五, 319102020332=李四, 319102020331=张三, 319102020330=政然}
HashMapDemo2 点击查看代码
package Map.HashMap;
import java.util.*;
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 this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
"}";
}
}
public class HashMapDemo2 {
public static void main(String[] args) {
/*
* 存储数据,每位学生(姓名,年龄)都有自己的家庭住址。
* 学生和地址有对应关系,将学生对象和家庭住址存储到map集合中。学生作为键, 家庭住址作为值。
* 要求:学生姓名相同并且年龄相同视为同一名学生,不能重复存储
*/
/**
* 学生姓名 年龄 家庭住址
* 张美丽 18岁 北京市朝阳区阳光小区12号楼302室
* 王伟 20岁 上海市浦东新区海天花园8号楼506室
* 李磊 19岁 广州市天河区华景新城15号别墅
* 陈小芳 17岁 成都市武侯区锦江花园5栋104室
* 赵阳 21岁 南京市鼓楼区中山路22号公寓401室
*
*/
Student[] students = new Student[] {
new Student("张美丽", 18),
new Student("王伟", 20),
new Student("李磊", 19),
new Student("陈小芳", 17),
new Student("赵阳", 21),
new Student("张美丽", 18),
new Student("王伟", 20),
new Student("李磊", 19),
new Student("陈小芳", 17),
new Student("赵阳", 21)
};
String[] address = new String[] {
"北京市朝阳区阳光小区12号楼302室",
"上海市浦东新区海天花园8号楼506室",
"广州市天河区华景新城15号别墅",
"成都市武侯区锦江花园5栋104室",
"南京市鼓楼区中山路22号公寓401室",
"上海市徐汇区龙华路188号鸿运大厦15楼1503室",
"广州市越秀区农林路36号绿地中心18栋2201室",
"成都市高新区天府大道1980号华润中心3栋808室",
"深圳市福田区福虹路28号富士康大厦10楼1005室",
"杭州市西湖区文一西路78号西溪国际大厦5栋602室"
};
Map<Student, String> map = new HashMap<Student, String>();
initMap(map, students, address);
// 要达到去重效果,需要重写hashCode和equals方法
traverseMap(map);
}
private static void traverseMap(Map<Student, String> map) {
Set<Student> keySet = map.keySet();
for (Student student : keySet) {
System.out.println(student + " : " + map.get(student));
}
}
private static void initMap(Map<Student, String> map, Student[] students, String[] address) {
for (int i = 0; i < students.length; i++) {
Student student = students[i];
String adr = address[i];
map.put(student, adr);
}
}
}
运行结果
{ name='张美丽', age='18'} : 上海市徐汇区龙华路188号鸿运大厦15楼1503室
{ name='王伟', age='20'} : 广州市越秀区农林路36号绿地中心18栋2201室
{ name='李磊', age='19'} : 成都市高新区天府大道1980号华润中心3栋808室
{ name='赵阳', age='21'} : 杭州市西湖区文一西路78号西溪国际大厦5栋602室
{ name='陈小芳', age='17'} : 深圳市福田区福虹路28号富士康大厦10楼1005室
LinkedHashMap
LinkedHashMapDemo 点击查看代码
package Map.LinkedHashMap;
import java.util.*;
public class LinkedHashMapDemo1 {
/**
* 底层结构是有链表和哈希表结构,具有键唯一,有序特点
* LinkedHashMap类 , 底层采用的数据结构 : 链表+哈希表
* 特点 :
* 1 元素唯一
* 2 元素有序
*
* @param args
*/
public static void main(String[] args) {
Map<String, String> LinkedHashMap = new LinkedHashMap<>();
/*
* 学号: 2023001,姓名: 王小明
* 学号: 2023002,姓名: 李婷婷
* 学号: 2023003,姓名: 张阳
* 学号: 2023004,姓名: 赵鑫
* 学号: 2023005,姓名: 陈思思
*/
LinkedHashMap.put("2023001", "王小明");
LinkedHashMap.put("2023002", "李婷婷");
LinkedHashMap.put("2023003", "张阳");
LinkedHashMap.put("2023004", "赵鑫");
LinkedHashMap.put("2023005", "陈思思");
LinkedHashMap.put("2023004", "赵鑫");
LinkedHashMap.put("2023005", "陈思思");
System.out.println(LinkedHashMap);
Iterator<Map.Entry<String, String>> it = LinkedHashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
运行结果
{2023001=王小明, 2023002=李婷婷, 2023003=张阳, 2023004=赵鑫, 2023005=陈思思}
2023001 : 王小明
2023002 : 李婷婷
2023003 : 张阳
2023004 : 赵鑫
2023005 : 陈思思
TreeMap
TreeMapDemo1 点击查看代码
package Map.TreeMap;
import java.util.*;
public class TreeMapDemo1 {
/*
* 底层是有红黑树,具有键唯一,排序特点
* TreeMap的底层是红黑树实现的,有排序的能力,键去重。
* 可以自然排序(键所在的类要实现Comparable)
* 若自定义类没有自然排序功能,或自然排序功能不满足要求时。可以自定义比较器排序(Comparator)
*
*/
public static void main(String[] args) {
// 自然排序
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
treeMap1.put(3, "Three");
treeMap1.put(1, "One");
treeMap1.put(2, "Two");
System.out.println("自然排序:" + treeMap1);
// 自定义比较器排序
TreeMap<Integer, String> treeMap2 = new TreeMap<>((o1, o2) -> o2 - o1);
treeMap2.put(3, "Three");
treeMap2.put(1, "One");
treeMap2.put(2, "Two");
System.out.println("自定义比较器排序:" + treeMap2);
}
}
运行结果
自然排序:{1=One, 2=Two, 3=Three}
自定义比较器排序:{3=Three, 2=Two, 1=One}
TreeMapDemo2 点击查看代码
package Map.TreeMap;
import java.util.*;
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 this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public Student name(String name) {
setName(name);
return this;
}
public Student age(int age) {
setAge(age);
return this;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return Objects.equals(name, student.name) && age == student.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "{" +
" name='" + getName() + "'" +
", age='" + getAge() + "'" +
"}";
}
}
public class TreeMapDemo2 {
public static void main(String[] args) {
/*
* 需求:创建一个TreeMap集合,键是学生对象(Student),值是籍贯(String)。 学生属性姓名和年龄
* 要求按照年龄进行升序排序并遍历
*/
Student[] students = new Student[] {
new Student("张美丽", 18),
new Student("王伟", 20),
new Student("李磊", 19),
new Student("陈小芳", 17),
new Student("赵阳", 21),
};
String[] nativePlace = new String[] { "安徽安庆", "江苏无锡", "浙江杭州", "四川成都", "陕西咸阳" };
Map<Student, String> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getAge() - o2.getAge();
}
});
initMap(map, students, nativePlace);
traverseMap(map);
}
private static void traverseMap(Map<Student, String> map) {
Set<Map.Entry<Student, String>> entries = map.entrySet();
for (Map.Entry<Student, String> entry : entries) {
System.out.println(entry);
}
}
private static void initMap(Map<Student, String> map, Student[] students, String[] nativePlace) {
for (int i = 0; i < nativePlace.length; i++) {
Student student = students[i];
String place = nativePlace[i];
map.put(student, place);
}
}
}
运行结果
{ name='陈小芳', age='17'}=四川成都
{ name='张美丽', age='18'}=安徽安庆
{ name='李磊', age='19'}=浙江杭州
{ name='王伟', age='20'}=江苏无锡
{ name='赵阳', age='21'}=陕西咸阳
MapTest
MapFunction 点击查看代码
package Map.Map;
import java.util.*;
/**
* - public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。
* - public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
* - public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
* - public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
* - public boolean containKey(Object key): 判断该集合中是否有此键
*/
public class MapDemo1 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("中国科学技术大学", "张三");
map.put("南京航空航天大学", "李四");
map.put("北京航空航天大学", "王五");
map.put("南京邮电大学", "王二麻子");
map.put("北京外国语大学", "孙七");
map.put("首都对外经济贸易大学", "赵德柱");
traverseMap(map);
System.out.println("=========================================================================");
System.out.println(map.remove("南京邮电大学"));
System.out.println(map.get("首都对外经济贸易大学"));
Set<String> keySet = map.keySet();
System.out.println("所有学校名称:" + keySet);
System.out.println(map.containsKey("南京航空航天大学"));
map.entrySet().forEach(System.out::println);
}
private static void traverseMap(Map<String, String> map) {
for (String key : map.keySet()) {
System.out.println("学校名称:" + key + "\t\t\t\t\t 学生姓名:" + map.get(key));
}
}
}
运行结果
学校名称:北京航空航天大学 学生姓名:王五
学校名称:南京邮电大学 学生姓名:王二麻子
学校名称:中国科学技术大学 学生姓名:张三
学校名称:北京外国语大学 学生姓名:孙七
学校名称:首都对外经济贸易大学 学生姓名:赵德柱
学校名称:南京航空航天大学 学生姓名:李四
=========================================================================
王二麻子
赵德柱
所有学校名称:[北京航空航天大学, 中国科学技术大学, 北京外国语大学, 首都对外经济贸易大学, 南京航空航天大学]
true
北京航空航天大学=王五
中国科学技术大学=张三
北京外国语大学=孙七
首都对外经济贸易大学=赵德柱
南京航空航天大学=李四
MapTest 点击查看代码
package Map.Map;
import java.util.*;
public class MapTest {
public static void main(String[] args) {
/*
* 需求:字符串“aababcabcdabcde”
* 请统计字符串中每一个字符出现的次数,并按照以下格式输出
* 输出结果:
* a(5)b(4)c(3)d(2)e(1)
*
*/
/*
* Map集合中,键存字符,值存出现的次数
* 遍历字符串,得到每一个字符
* 到集合中看是否包含这个字符
* 如果不包含,表示是第一次出现
* 如果包含,表示不是第一次出现
*/
String str = new String("aababcabcdabcde");
HashMap<Character, Integer> hashmap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char key = str.charAt(i);
if (!hashmap.containsKey(key)) {
hashmap.put(key, 1);
} else {
hashmap.put(key, hashmap.get(key) + 1);
}
}
Set<Character> keyset = hashmap.keySet();
for (Character character : keyset) {
System.out.print(character + "(" + hashmap.get(character) + ")");
}
}
}
运行结果
a(5)b(4)c(3)d(2)e(1)
TraverseMap 点击查看代码
package Map.Map;
import java.util.*;
public class TraverseMap {
public static void main(String[] args) {
/*
* 第一种遍历方式 : 键找值方式
*
*/
Map<String, String> map = new HashMap<>();
String[] strings1 = new String[] { "周瑜", "孙策", "刘备", "诸葛亮" };
String[] strings2 = new String[] { "大乔", "小乔", "孙尚香", "黄月英" };
initMap(map, strings1, strings2);
// 第一种遍历方式 : 键找值方式
fun1(map);
System.out.println("======================================================");
// 第二种遍历方式 : 键值对对象遍历
fun2(map);
}
private static void fun2(Map<String, String> map) {
// 第二种遍历方式 : 键值对对象遍历
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
private static void initMap(Map<String, String> map, String[] strings1, String[] strings2) {
for (int i = 0, j = 0; i < strings1.length && j < strings2.length; i++, j++) {
map.put(strings1[i], strings2[j]);
}
}
private static void fun1(Map<String, String> map) {
// 第一种遍历方式 : 键找值方式
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + "-" + map.get(key));
}
}
}
运行结果
刘备-孙尚香
孙策-小乔
诸葛亮-黄月英
周瑜-大乔
======================================================
刘备-孙尚香
孙策-小乔
诸葛亮-黄月英
周瑜-大乔
Nesting_of_sets
List_Nested_List
List_Nested_ListDemo 点击查看代码
package Nesting_of_sets.List_Nested_List;
import java.util.*;
public class List_Nested_List {
public static void main(String[] args) {
/*
* 使用场景举例:一年级有多个班级,每个班级有多名学生。要求保存每个班级的学生姓名,
* 保存一个年级所有的班级信息
*
* 思路:
* 可以使用List集合保存一个班级的学生
* 可以使用List集合保存所有班级
*
* 因此我们可以定义集合如下:
* 班级:List<String>
* 年级:List<List<String>>
*
*/
// 创建班级集合
List<String> class1Students = new ArrayList<>();
// 添加学生
class1Students.add("Tom");
class1Students.add("Jerry");
class1Students.add("Spike");
// 创建班级集合
List<String> class2Students = new ArrayList<>();
// 添加学生
Collections.addAll(class2Students, "Tyke", "Butch", "Quacker", "Daffy", "Judy");
// 年级
List<List<String>> gradeClassList = new ArrayList<>();
// 添加班级
Collections.addAll(gradeClassList, class1Students, class2Students);
traverseList(gradeClassList);
}
private static void traverseList(List<List<String>> gradeClassList) {
// 遍历年级集合
// 三种遍历方法
for (List<String> classes : gradeClassList) {
for (String stuName : classes) {
System.out.println("姓名:" + stuName);
}
System.out.println("====================");
}
}
}
运行结果
姓名:Tom
姓名:Jerry
姓名:Spike
====================
姓名:Tyke
姓名:Butch
姓名:Quacker
姓名:Daffy
姓名:Judy
====================
List_Nested_MapDemo
List_Nested_MapDemo 点击查看代码
package Nesting_of_sets.List_Nested_Map;
/*
*
* 使用场景举例:一年级有多个班级,每个班级有多名学生。要求保存每个班级的学生姓名,姓名有与之对应的学号,保存一年级所有的班级信息。
思路:
可以使用Map集合保存一个班级的学生(键是学号,值是名字)
可以使用List集合保存所有班级
因此我们可以定义集合如下:
班级:Map<String,String> 键是学号,值是姓名
年级:List<Map<String,String>>保存每个班级的信息
*/
import java.util.*;
public class List_Nested_Map {
public static void main(String[] args) {
Map<String, String> class1Students = new HashMap<>();
class1Students.put("001", "Tom");
class1Students.put("002", "Jerry");
class1Students.put("003", "Spike");
Map<String, String> class2Students = new HashMap<>();
class2Students.put("004", "Tyke");
class2Students.put("005", "Butch");
class2Students.put("006", "Quacker");
Map<String, String> class3Students = new HashMap<>();
class3Students.put("007", "Nibbles");
class3Students.put("008", "Sneezy");
class3Students.put("009", "Dopey");
List<Map<String, String>> gradeClasses = new ArrayList<>();
Collections.addAll(gradeClasses, class1Students, class2Students, class3Students);
traverseMap(gradeClasses);
}
private static void traverseMap(List<Map<String, String>> gradeClasses) {
for (Map<String, String> classStudents : gradeClasses) {
for (Map.Entry<String, String> entry : classStudents.entrySet()) {
System.out.println("学号:" + entry.getKey() + ",姓名:" + entry.getValue());
}
System.out.println("================================================");
}
for (Map<String, String> map : gradeClasses) {
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println("学号:" + key + ",姓名:" + map.get(key));
}
System.out.println("================================================");
}
}
}
运行结果
学号:001,姓名:Tom
学号:002,姓名:Jerry
学号:003,姓名:Spike
================================================
学号:004,姓名:Tyke
学号:005,姓名:Butch
学号:006,姓名:Quacker
================================================
学号:007,姓名:Nibbles
学号:008,姓名:Sneezy
学号:009,姓名:Dopey
================================================
学号:001,姓名:Tom
学号:002,姓名:Jerry
学号:003,姓名:Spike
================================================
学号:004,姓名:Tyke
学号:005,姓名:Butch
学号:006,姓名:Quacker
================================================
学号:007,姓名:Nibbles
学号:008,姓名:Sneezy
学号:009,姓名:Dopey
================================================
Map_Nested_Map
Map_Nested_MapDemo 点击查看代码
package Nesting_of_sets.Map_Nested_Map;
import java.util.*;
/*
*
* 使用场景举例:一个年级有多个班级,每个班级有多名学生。要求保存每个班级的学生姓名,姓名有与之对应的学号,保存一年级所有的班级信息,班级有与之对应的班级名称。
思路:
可以使用Map集合保存一个班级的学生(键是学号,值是名字)
可以使用Map集合保存所有班级(键是班级名称,值是班级集合信息)
因此我们可以定义集合如下:
班级: Map<String,String> 键:学号,值:姓名
年级: Map<String,Map<String,String>> 键:班级名称,值:具体班级信息
*/
public class Map_Nested_Map {
public static void main(String[] args) {
// 班级名称 Map<String, String> 键:学号,值:姓名
Map<String, Map<String, String>> gradeMap = new HashMap<>();
Map<String, String> class1Map = new HashMap<>();
class1Map.put("001", "Tom");
class1Map.put("002", "Jerry");
class1Map.put("003", "Spike");
class1Map.put("004", "Lily");
Map<String, String> class2Map = new HashMap<>();
class2Map.put("001", "Tyke");
class2Map.put("002", "Butch");
class2Map.put("003", "Toodles");
class2Map.put("004", "Quacker");
Map<String, String> class3Map = new HashMap<>();
class3Map.put("001", "Tuffy");
class3Map.put("002", "Puffy");
class3Map.put("003", "Fluffy");
class3Map.put("004", "Bubbles");
class3Map.put("005", "Buddy");
gradeMap.put("class1", class1Map);
gradeMap.put("class2", class2Map);
gradeMap.put("class3", class3Map);
traverseGradeMap(gradeMap);
}
private static void traverseGradeMap(Map<String, Map<String, String>> gradeMap) {
// for (Map.Entry<String, Map<String, String>> entry : gradeMap.entrySet()) {
// System.out.println("Class Name: " + entry.getKey());
// Map<String, String> classMap = entry.getValue();
// for (Map.Entry<String, String> studentEntry : classMap.entrySet()) {
// System.out.println("Student ID: " + studentEntry.getKey() + ", Student Name:
// " + studentEntry.getValue());
// }
// System.out.println("=============================================================");
// }
Set<String> keySet1 = gradeMap.keySet();// 拿到每个班级的名称
for (String className : keySet1) {
System.out.println("Class Name:" + className);
Set<String> keySet2 = gradeMap.get(className).keySet();// 拿到每个班级的学生信息
for (String studentId : keySet2) {
System.out.println("Student ID:" + studentId + ", Student Name:" + gradeMap.get(className).get(studentId));
}
System.out.println("=============================================================");
}
}
}
运行结果
Class Name:class3
Student ID:001, Student Name:Tuffy
Student ID:002, Student Name:Puffy
Student ID:003, Student Name:Fluffy
Student ID:004, Student Name:Bubbles
Student ID:005, Student Name:Buddy
=============================================================
Class Name:class2
Student ID:001, Student Name:Tyke
Student ID:002, Student Name:Butch
Student ID:003, Student Name:Toodles
Student ID:004, Student Name:Quacker
=============================================================
Class Name:class1
Student ID:001, Student Name:Tom
Student ID:002, Student Name:Jerry
Student ID:003, Student Name:Spike
Student ID:004, Student Name:Lily
=============================================================