List常用方法介绍
package Demo05;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Demo01List {
public static void main(String[] args) {
List<String>list =new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("a");
System.out.println(list);
list.add(3,"lcz");
System.out.println(list);
String removE=list.remove(3);
System.out.println(removE);
System.out.println(list);
String setE=list.set(4,"A");
System.out.println("被替换的元素"+setE);
System.out.println(list);
for (int i = 0; i <list.size() ; i++) {
String s=list.get(i);
System.out.println(s);
}
System.out.println("------------");
Iterator<String> it=list.iterator();
while(it.hasNext()){
String s=it.next();
System.out.println(s);
}
System.out.println("------------");
for (String s:list){
System.out.println(s);
}
}
}
package Demo05;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Demo01Set {
public static void main(String[] args) {
Set<Integer> set=new HashSet<>();
set.add(1);
set.add(3);
set.add(2);
set.add(1);
Iterator<Integer> it=set.iterator();
while (it.hasNext()){
Integer n=it.next();
System.out.println(n);
}
System.out.println("---------");
for(Integer i:set){
System.out.println(i);
}
}
}
package Demo05;
public class Demo01Hashcod {
public static void main(String[] args) {
Person p1=new Person();
int h1=p1.hashCode();
System.out.println(h1);
Person p2=new Person();
int h2=p2.hashCode();
System.out.println(h2);
System.out.println(p1);
System.out.println(p2);
System.out.println(p1==p2);
System.out.println("重地".hashCode());
System.out.println("通话".hashCode());
}
}
package Demo06;
import java.util.HashSet;
public class Demo01HashSetSavePerson {
public static void main(String[] args) {
HashSet<Person> set=new HashSet<>();
Person p1=new Person("老村长",21);
Person p2=new Person("老村长",20);
Person p3=new Person("老村长",21);
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println(p1.hashCode());//460141958
System.out.println(p3.hashCode());//1956725890
System.out.println(p1==p2);//false
System.out.println(p1.equals(p2));//false
System.out.println(set);
}
}
package Demo06;
import java.util.Objects;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name,int age) {
this.name=name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}