Collections 工具类
* Collection与Collections区别
Collection 接口,(大部分集合类的实现接口)
Collections 工具类(针对列表)
* Collections工具类常用方法
1.父类的引用指向子类的对象(复习) 2.sort(List list)排序 3.sort(List list, Comparator comparator);排序 4.binarySearch,搜索指定元素索引,前提列表必须有序 5.reverse反转 6.重新洗牌shuffle方法 7.swap交换,交换两个索引位置元素,Collections.swap(list, 1, 2);
* 测试Collections工具类方法代码:
package method; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/***
* 1.父类的引用指向子类的对象
* 2.sort(List list)排序
* 3.sort(List list, Comparator comparator);排序
* 4.binarySearch,搜索指定元素索引,前提列表必须有序
* 5.reverse反转
* 6.重新洗牌shuffle
* 7.swap交换,交换两个索引位置元素,Collections.swap(list, 1, 2);
* @author Administrator
*
*/
public class CollectionsDemo {
public static void main(String[] args) {
List list=new ArrayList(); //添加测试数据
list.add("a");
list.add("b");
list.add("d");
list.add("c");
list.add("e"); System.out.println(Arrays.toString(list.toArray()));
//sort排序,升序
Collections.sort(list); System.out.println(Arrays.toString(list.toArray())); //使用sort降序排序
Collections.sort(list, new Comparator<String>(){ @Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
int result=o2.length()-o1.length();
int length=result>0?o2.length():o1.length(); char[]a1=o1.toCharArray();
char[]a2=o2.toCharArray();
for(int i=0;i<length;i++){
if(a1[i]>a2[i]){
return -1;
}else if(a1[i]==a2[i]){
return 0;
}else{
return 1;
}
}
return result;
}
}); System.out.println(Arrays.toString(list.toArray()));
//二分法检测元素索引
int indexResult = Collections.binarySearch(list, "c"); System.out.println(indexResult); //reverse反转
Collections.reverse(list);
System.out.println(Arrays.toString(list.toArray())); //重新洗牌shuffle
Collections.shuffle(list);
System.out.println(Arrays.toString(list.toArray())); //swap交换,交换两个索引位置元素
Collections.swap(list, 1, 2);
System.out.println(Arrays.toString(list.toArray()));
}
}
Collections常用方法测试
* 模拟斗地主,发牌代码
package method; import java.util.ArrayList;
import java.util.Collections; /***
* 模拟斗地主,洗牌
* @author Administrator
*
*/
public class Collections_card { public static void main(String[] args) {
ArrayList cards = new ArrayList(); ArrayList play1 = new ArrayList();
ArrayList play2 = new ArrayList();
ArrayList play3 = new ArrayList(); ArrayList dipai = new ArrayList();
//54张牌
for(int i=0;i<54;i++){
cards.add(i);
}
Collections.shuffle(cards);
//三个玩家分牌
for(int i=0;i<51;i+=3){
play1.add(cards.get(i));
play2.add(cards.get(i+1));
play3.add(cards.get(i+2));
}
//底牌
for(int i=51;i<54;i++){
dipai.add(cards.get(i));
} //输出检查效果
System.out.println("玩家一:"+play1);
System.out.println("玩家二:"+play2);
System.out.println("玩家三:"+play3);
System.out.println("底牌:"+dipai);
}
}
模拟斗地主发牌