package com.company.collection;
import java.util.*;
public class CollectionTest {
public static void main(String[] args){
CollectionTest.hashSetDemo();
}
public static void collectionDemo(){
Collection<String> col = new ArrayList<>();
col.add("红的");
col.add("黄的");
col.add("绿的");
Iterator<String> it = col.iterator();
System.out.print("集合中元素:");
while(it.hasNext()){
String s = it.next();
System.out.print(" " + s);
}
System.out.println();
col.remove("黄的");
System.out.print("集合中元素:");
for(String s : col){
System.out.print(" " + s);
}
System.out.println();
System.out.println("集合中是否包含“黄的”对象:" + col.contains("黄的"));
System.out.println("集合中元素个数:" + col.size());
Object[] object = col.toArray();
System.out.print("数组object中元素:");
for(int i=0;i<object.length;i++){
System.out.print(" " + object[i]);
}
System.out.println();
}
public static void listDemo(){
List<String> list = new ArrayList<>();
list.add("白的");
list.add("蓝的");
list.add("粉的");
list.add(1,"黑的");
Iterator<String> it = list.iterator();
System.out.print("集合list中元素有:");
while(it.hasNext()){
String s = it.next();
System.out.print(" " + s);
}
System.out.println();
System.out.println("集合list中第三位元素是:" + list.get(2));
System.out.println("集合list中第三位元素更新为“蓝色”:" + list.set(2,"蓝色"));
list.remove(3);
System.out.print("集合list中元素有:" );
for(String s : list){
System.out.print(" " + s);
}
}
public static void linkedListDemo(){
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("蓝的");
linkedList.add("绿的");
linkedList.add("粉的");
linkedList.addFirst("红的");
linkedList.addLast("黄的");
System.out.println(linkedList);
System.out.println("表头元素为:" + linkedList.getFirst());
System.out.println("表尾元素为:" + linkedList.getLast());
}
public static void setDemo(){
Set<String> set = new HashSet<>();
set.add("红的");
set.add("黄的");
set.add("绿的");
set.add("红的");
System.out.println(set);
}
public static void hashSetDemo(){
HashSet<Student> hashSet = new HashSet<>();
Student stu = new Student("张三",21);
hashSet.add(stu);
hashSet.add(new Student("李四",23));
hashSet.add(new Student("王五",22));
hashSet.add(new Student("李四",23));
for(Student stu1 : hashSet){
System.out.println(stu1.getName()+stu1.getAge());
}
}
}
package com.company.collection;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student(String name, int age){
this.age = age;
this.name = name;
}
public String getName(){
return this.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 || this.getClass() != o.getClass())
return false;
Student s = (Student)o;
return age == s.age && Objects.equals(name,s.name);
}
@Override
public int hashCode(){
return Objects.hash(name,age);
}
}