java 集合 之 equals contain

来源:互联网 发布:淘宝旺旺聊天刷单禁词 编辑:程序博客网 时间:2024/06/05 04:15

.boolean List.contain(obj);//判断List中是否含有此对象(多equals()方法调用判断)返回布尔值;可以通过重写equals方法改写contain的判断方式(要考虑null的情况)Scanner若经常调用,可以作为类的属性之一,并在构造函数中创建对象。
.containsAll(collection cl);返回是否包含cl所有元素Set小记:set.contains(obj)返回是否包含对象(机制:equals+HashCode判断),自定义的判断方法要改写equals方法与HashCode方法;

重写equals方法模板例子如下:

Course类型的equals方法public boolean equals(Object obj){if(this==obj){return true;}if(obj==null){return false;}if(!(obj instanceof Course)){return false;}Course course=(Course)obj;if(course.name==null){if(this.name==null){return true;}else{return false;}}else{if(couse.name.equals(this.name)){return true;}else{return false;}}}
HashSet的contains()方法的实现过程:先调用set中每个元素的hashCode()方法,比较返回的哈希码,哈希码相同再调用equals方法,当两者都相同时才返回true
list 与 set 中contain()方法调用机制:list 中的contain()方法是拿到list中的每个对象来调用Object类中的equals()方法Set  中的contain()方法是拿到list中的每个元素来先调用hashcode()方法来返回哈希码值,当哈希码的值相等时,再调用equals()方法,当比较的元素此时也相同时,才会返回true。因此调用Set中的contain()方法时,需要对hashcode()方法及equals()方法进行重写。

1.通过List.indexOf(OBJ obj)方法获得对象的索引位置(obj中某一元素用equals()判断后true即可获得首个索引)2.List.lastIndexOf(OBJ obj)方法获得最后一个相等对象的索引位置3.indexOf 与lastIndexOf方法找不到对应的值的时候返回-1;
Map中通过containsKey()方法和containsValue()方法来判断键和值是否存在Map 中对对象进行了 Key 标记,通过 get(Key)可以取得对应的对象Map 的containsValue()方法的参数是 Object 对象,因为Map 的 Value 值是对象元素Map 的containsKey()方法取得 Map 映射的 Key 值List中的contains()方法调用equals()方法来进行比较。所以要重写Hashcode和equals方法跟 List 的 contains()方法一样,Map 中的 containsValue()方法也会调用每个 Value 值的 equals()方法去和参数对象比较id 是string类型 contains方法使用equals方法 来比较,所以值相等就返回tureValue 是Student类型,自己定义的,默认的contains方法中的equals方法,比较的是两个引用是否一样,所以要重写equals方法由于是比较两student类型是否相同,所以要做Student类中重写equals方法
怎么生成随机字符

public void testSort2() {List<String> strings = new ArrayList<String>();String str = "0123456789abcdefghijklmnobqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";Random random = new Random();for (int a = 0; a < 10; a++) {StringBuilder builder = new StringBuilder();do {int j = random.nextInt(10) + 1;for (int i = 0; i < j; i++) {builder.append(str.charAt(random.nextInt(str.length())));

}} while (strings.contains(builder));System.out.println("将要添加字符串"+builder);String s=builder.toString();strings.add(s);}System.out.println("-----------排序前------------");for (String string : strings) {System.out.println("元素"+string);}Collections.sort(strings);System.out.println("-----------排序后-----------");for (String string : strings) {System.out.println("元素"+string);}}public static void main(String[] args) {CollectionTest collectionTest = new CollectionTest();// collectionTest.testSort1();collectionTest.testSort2();}


对Integer泛型的list进行排序-->
List<Integer>  integerList=new ArrayList<Integer>();Random random = new Random(); // 创建一个新的随机生成器Integer k;for(int i=0;i<10;i++){    do{        k=random.nextInt(100);// 随机生成100以内的整数    }while(integerList.contains(k)); //若已存在,循环运行,生成其他值    integerList.add(k); }

思路:

给泛型为Integer的list里插入十个100以内的不重复的随机数。Random类的nextInt(100)方法可以返回100以内的随机数。Collections.sort()方法给Integer list按数字升序排列顺序。


Comparable接口-----可比较的1.实现该接口表示:这个类的实例可以比较大小,可以进行自然排序2.定义了默认的比较规则3.其实现类需实现compareTo()方法compareTo()方法返回正数表示打,负数表示小,0表示相等Comparator接口-----比较工具接口1.用于定义临时比较规则,而不是默认比较规则2.其实现类需要实现compare()方法3.Comparator和Comparable都是Java集合框架的成员Java集合框架:Collection接口、Collections工具类、Map接口、Comparator接口、Comparable接口

1. 创建一副扑克牌,不考虑大小王2. 创建两名玩家,玩家至少要有ID、姓名、手牌等属性,手牌为扑克牌的集合3. 洗牌,将之前创建的扑克牌顺序打乱(说明是有序的)4. 发牌,将洗牌之后的扑克牌集合,从第一张开始,发给两名玩家,按照一人一张的方式,每人发两张5. 开始游戏,比大小,取两人各自的点数最大的牌进行比较,点数大的赢,若大小相同比花色(黑红梅方)


package com.xk; 

public class Poker

 { 

public String color; 

public String points;

 public Poker(String color,String points){ this.color=color; this.points=points; } 

@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((points == null) ? 0 : points.hashCode()); result = prime * result + ((color == null) ? 0 : color.hashCode()); return result; } 

@Override public boolean equals(Object obj) { 

if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; 

Poker other = (Poker) obj; if (points == null) { 

if (other.points != null) return false; } else if (!points.equals(other.points)) return false; 

if (color == null) 

{ if (other.color != null) return false; }

 else if (!color.equals(other.color)) 

return false; return true; } }


package com.xk; import java.util.ArrayList; import java.util.List; 

public class Player { 

public int id; public String name; 

public List<Poker> handCards=new ArrayList<>(); 

public Player(int id,String name){ 

this.id=id; this.name=name;

 }

 }



package com.xk; import java.util.Comparator; 

public class CompareToPoker implements Comparator<Poker>

 { @Override public int compare(Poker o1, Poker o2) { 

// TODO Auto-generated method stub String[] color = {"方片", "梅花", "红桃", "黑桃"};

 String[] point = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J","Q","K", "A"}; 

int temp1 = 0; int temp2 = 0; for(int i=0;i<point.length;i++){ if(o1.points.equals(point[i])) temp1 += i*10; if(o2.points.equals(point[i])) temp2 += i*10; } 

for(int i=0;i<color.length;i++){ if(o1.color.equals(color[i])) temp1 += i; 

if(o2.color.equals(color[i])) temp2 += i; } 

if( temp1 > temp2) return -1; 

if( temp1 < temp2 ) 

return 1; return 0; } }


public class GameStart{

 String[] point=new String[]{"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; 

String[] color=new String[]{"黑桃","红桃","梅花","方块"}; 

Scanner input = new Scanner(System.in); 

List<Poker> pokerList=new ArrayList<>(); 

List<Player> playerList=new ArrayList<>(); 

public void initialize(){ for(int i=0;i<4;i++) { for(int j=0;j<13;j++) { 

pokerList.add(new Poker(color[i],point[j])); } } 

System.out.println("------------创建扑克牌-------------"); 

int i=0; for(Poker poker : pokerList){ System.out.print(poker.color+poker.points+" ");

 i++; if(i%13==0){ System.out.println(""); } } } public void shuffle(){ System.out.println("-------------开始洗牌-------------"); 

Collections.shuffle(pokerList);//shuffle List随机排序 System.out.println("-------------洗牌完成-------------"); } 

public void sort(){ Collections.sort(playerList.get(0).handCards,new CompareToPoker());

 Collections.sort(playerList.get(1).handCards,new CompareToPoker()); 

System.out.println(playerList.get(0).name+"最大手牌:"+playerList.get(0).handCards.get(0).color+playerList.get(0).handCards.get(0).points); System.out.println(playerList.get(1).name+"最大手牌:"+playerList.get(1).handCards.get(0).color+playerList.get(1).handCards.get(0).points); } 

public void print(){ System.out.println("----------玩家各自手牌-------------"); 

for(Player player : playerList){ System.out.print(player.name+":"); 

for(Poker poker : player.handCards){ System.out.print("["+poker.color+poker.points+"]"); } System.out.println(""); } }

 public void compareToPonint(){ System.out.println("--------------获胜方--------------"); 

List<Poker> maxPoker = new ArrayList<Poker>(); 

List<Poker> minPoker = new ArrayList<Poker>();

 maxPoker.add(playerList.get(0).handCards.get(0)); 

maxPoker.add(playerList.get(1).handCards.get(0)); 

minPoker.add(playerList.get(0).handCards.get(1)); 

minPoker.add(playerList.get(1).handCards.get(1)); 

Collections.sort(maxPoker,new CompareToPoker()); 

Collections.sort(minPoker,new CompareToPoker()); 

/* * 判断最大牌点数是否相等 * 判断最小牌点数是否相等 * 判断最大牌花色 * 判断最小牌花色 * */ if(maxPoker.get(0).points.equals(maxPoker.get(1).points)){

 if(minPoker.get(0).points.equals(minPoker.get(1).points)){ 

if(maxPoker.get(0).equals(playerList.get(0).handCards.get(0))){

 System.out.println("红方获胜\tWinner:"+playerList.get(0).name); 

}else{ 

System.out.println("蓝方获胜\tWinner:"+playerList.get(1).name); 

} }else{ 

if(minPoker.get(0).equals(playerList.get(0).handCards.get(1))){ 

System.out.println("红方获胜\tWinner:"+playerList.get(0).name); 

}else{ 

System.out.println("蓝方获胜\tWinner:"+playerList.get(1).name); } } 

}else if(maxPoker.get(0).equals(playerList.get(0).handCards.get(0))){ 

System.out.println("红方获胜\tWinner:"+playerList.get(0).name); }else{ 

System.out.println("蓝方获胜\tWinner:"+playerList.get(1).name); 

} } 

public void playerSet(){ 

System.out.println("-----------创建两名玩家------------");

 for(int i=1;i<=2;i++){ System.out.println("输入玩家"+i+"的id:"); 

int id=0; try{ id=scanf(); 

}catch(Exception e){ 

System.out.println(e.getMessage()); i--; continue;

 } System.out.println("输入玩家"+i+"的姓名:"); String name=input.next(); 

playerList.add(new Player(id,name)); } 

input.close(); 

System.out.println("----------Game Start!-----------\n红方玩家\t蓝方玩家"); 

for(Player p : playerList){ System.out.print(p.name+"\t"); } } 

public int scanf() throws Exception{

 try{ int in=input.nextInt(); return in; }catch(Exception e){

input=new Scanner(System.in); throw new Exception("输入异常,请输入整数类型的ID!");

 } }

 public void deal(){ System.out.println("\n-------------开始发牌-------------"); 

System.out.println(playerList.get(0).name+"拿牌");

 playerList.get(0).handCards.add(pokerList.get(0));

 System.out.println(playerList.get(1).name+"拿牌"); 

playerList.get(1).handCards.add(pokerList.get(1)); 

System.out.println(playerList.get(0).name+"拿牌");

 playerList.get(0).handCards.add(pokerList.get(2)); 

System.out.println(playerList.get(1).name+"拿牌"); 

playerList.get(1).handCards.add(pokerList.get(3)); 

System.out.println("------------发牌结束--------------"); } 

public static void main(String[] args) { 

System.out.println("----------欢迎进入纸牌大战----------"); 

GameStart gs=new GameStart(); 

gs.initialize(); 

gs.shuffle(); 

gs.playerSet(); 

gs.deal(); 

gs.sort(); 

gs.compareToPonint(); 

gs.print(); 

System.out.println("-------------游戏结束-------------"); } }






原创粉丝点击