1.迭代器:Iterator和ListIterator
package bilibili.chapter16;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Iiterator {
public static void main(String []args){
List<String>list = new LinkedList<>();
list.add("yzq");
list.add("yxc");
list.add("yzz");
ListIterator<String>iterator = list.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
}
2.Collections集合类
(1)字符串逆序–使用compareTo
public class Iiterator {
public static void main(String []args){
List<String>list = new LinkedList<>();
list.add("1yzq");
list.add("2yxc");
list.add("4yzz");
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(list);
}
}
(2)类排序
public class Iiterator {
public static void main(String []args){
List<String>list = new LinkedList<>();
list.add("1yzq");
list.add("2yxc");
list.add("4yzz");
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(list);
List<Person>list2 = new ArrayList<>();
list2.add(new Person(1,"yzq",22));
list2.add(new Person(2,"yxc",25));
list2.add(new Person(2,"abb",25));
list2.add(new Person(3,"yzz",20));
Collections.sort(list2, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if(o1.getID()==o2.getID()){
return o1.getName().compareTo(o2.getName());
}else{
return o1.getID()-o2.getID();
}
}
});
System.out.println(list2);
}
}
3.斗地主案例
public class Homework {
public static void main(String[] args) {
ArrayList<String>colors = new ArrayList<>(Arrays.asList("♠","♥","♣","♦"));
ArrayList<String>number = new ArrayList<>();
ArrayList<String>pokes = new ArrayList<>();
ArrayList<String>last = new ArrayList<>();
ArrayList<String>person1 = new ArrayList<>();
ArrayList<String>person2 = new ArrayList<>();
ArrayList<String>person3 = new ArrayList<>();
for(int i=2;i<=10;i++){
number.add(i+" ");
}
number.addAll(Arrays.asList("J","Q","K","A"));
for(String color:colors){
for(String num:number) {
pokes.add(color + num);
}
}
//System.out.println(pokes);
pokes.addAll(Arrays.asList("大王","小王"));
Collections.shuffle(pokes);
for (int i=0;i<pokes.size();i++){
String s = pokes.get(i);
if(i>pokes.size()-3){
last.add(s);
}else if(i%3==0){
person1.add(s);
}else if(i%3==1){
person2.add(s);
}else {
person3.add(s);
}
}
System.out.println("第一个人的牌:");
System.out.println(person1);
System.out.println("第二个人的牌:");
System.out.println(person2);
System.out.println("第三个人的牌:");
System.out.println(person3);
}
}