集合笔试题
1.产生10个1-20之间的随机数,要求随机数不能重复(List 和 Set 分别实现)
分析:1.创建一个 ArrayList 对象
2.如果 ArrayList 对象长度小于 10
3.在循环中,创建一个 Random 对象,产生 1-20 之间的随机数
4. 通过 ArrayList 对象 d constains 方法判断,该随机数是否存在于集合中,不存在则加入,存在则放弃。
代码:
1.List
package com.neuedu.collection;
import java.util.ArrayList;
import java.util.Random;
public class Demo1 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
while(list.size() < 10){
Random random = new Random();
int nextInt = random.nextInt(20) + 1;
if(!list.contains(nextInt)) {
list.add(nextInt);
}
}
System.out.println(list);
}
}
输出:
2.Set (无序【添加顺序和打印顺序不一致】、不重复)
package com.neuedu.collection;
import java.util.HashSet;
import java.util.Set;
public class Demo2 {
public static void main(String[] args) {
Set set = new HashSet<Integer>();
while(set.size() < 10) {
int random = (int)(Math.random() * 20) + 1;
set.add(random);
}
System.out.println(set);
}
}
输出:
拓展:当两个内容相同则输出一个,不同则都输出
hashcode: 根据一个对象,通过一定的算法,计算出一个 32位 的 2进制 表示的数据(不定长数据 转换 定长数据)
Object hashcode(默认的hashcode):根据对象在内存的地址来计算 hashcode 值(基本都不相同)
name 是string 类型 ,string 类型重写 hashcode ,当字符串内容相同则 hashcode 值相同(属性相关)
set 结构:
竖:hashtable(hash 桶)里面的小格(hashcode),当hashcode 值相同时才会放到同一个小格里面;
横:LinkedList(链表),里面的小格(equal 后的值),若二者相同则表示在链表的同一格里面,重复的不在添加到小格中;如二者不同则不在同一格里面,将不同的放在后面的小格里面。
package com.neuedu.collection;
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<Person> set = new HashSet<Person>();
Person p1 = new Person("林青霞", 50);
Person p2 = new Person("林青霞", 40);
set.add(p1);
set.add(p2);
System.out.println(set);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
return name.hashCode() + age;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Person)){
return false;
}
Person person = (Person)obj;
if(this.name.equals(person.name) && this.age == person.age) {
return true;
}
return false;
}
}
输出:
2.键盘录入5个学生信息(姓名、语文成绩、数学成绩、英语成绩)按照总分从高到低的顺序(若总分相同,则按照语文、数学、英语的成绩进行倒序)
二叉树:24 18 30 16 20 28 35
中序遍历(详解) :左 中 右 16 18 20 24 28 30 35
package com.neuedu.collection;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Demo3 {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
Scanner scanner = new Scanner(System.in);
for(int i = 1; i <= 5; i++) {
System.out.println("请输入第" + i + "个学生的信息");
System.out.println("姓名:");
String name = scanner.next();
System.out.println("语文 成绩:");
int chinese = scanner.nextInt();
System.out.println("数学成绩:");
int math = scanner.nextInt();
System.out.println("英语成绩:");
int english = scanner.nextInt();
Student student = new Student(name, chinese, math, english);
treeSet.add(student);
}
System.out.println("学生成绩录入完毕");
System.out.println("按照分数排序后的结果是:");
System.out.println(treeSet);
}
}
class Student implements Comparable<Student>{
private String name;
private int chinese;
private int math;
private int english;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getTotal() {
return chinese + english + math;
}
@Override
public String toString() {
return "Student [name=" + name + ", chinese=" + chinese + ", math=" + math + ", english=" + english + "]";
}
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
@Override
public int compareTo(Student o) {
int temp = o.getTotal() - this.getTotal();
if(temp == 0) {
temp = o.chinese - this.chinese;
}
if(temp == 0) {
temp = o.math - this.math;
}
if(temp == 0) {
temp = o.english - this.english;
}
/*temp = (temp != 0 ? temp : (o.chinese - this.chinese));
temp = (temp != 0 ? temp : (o.math - this.math));
temp = (temp != 0 ? temp : (o.english - this.english));*/
return temp;
}
}
输出:(只有2名学生)
3.“aababcabcdabcde”获取字符串中每个字母出现的次数,要求结果 a(5) b(4) c(3)
分析:1.将字符串转换成一个字符数组
2.对字符数组进行遍历,放到 Set 集合中
package com.neuedu.collection;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
public class Demo4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串");
String str = scanner.next();
TreeSet<Character> treeSet = new TreeSet<>();
for(int i = 0; i < str.length(); i++) {
treeSet.add(str.charAt(i));
}
System.out.println(treeSet);
for(Character c : treeSet) {
int count = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == c) {
count++;
}
}
System.out.print(c+"(" + count + ") " );
}
}
}
输出:
方法二:
package com.neuedu.collection;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
public class Demo4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符串");
String str = scanner.next();
TreeMap<Character, Integer> map = new TreeMap<>();
//遍历字符串
for(int i = 0; i < str.length(); i++) {
//获取每个字符
Character key = str.charAt(i);
//判断map中是否包含该字符,如果不包含,value=1,
if(!map.containsKey(key)) {
map.put(key, 1);
}else {//如果map中已经包含改字符,则取出原来的值+1
map.put(key, map.get(key) + 1);
}
}
StringBuffer sb = new StringBuffer();
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for(Entry<Character, Integer> entry : entrySet) {
sb.append(entry.getKey()).append("(").append(entry.getValue()).append(") ");
}
System.out.println(sb.toString());
}
输出:
标准方法:
//“aababcabcdabcde”获取字符串中每个字母出现的次数,要求结果 a(5) b(4) c
package com.hd.file;
import java.util.Set;
import java.util.TreeMap;
public class demo3 {
public static void main(String[] args) {
String str = "aababcabcdabcde";
TreeMap<Character,Integer> map = new TreeMap<Character,Integer>();
char[] chs = str.toCharArray();
for(Character ch:chs){
Integer value = map.get(ch);
if(value==null){
map.put(ch, 1);
}else{
value++;
map.put(ch, value);
}
}
Set<Character> set = map.keySet();
StringBuilder sb = new StringBuilder();
for(Character s:set){
Integer value = map.get(s);
sb.append(s).append("(").append(value).append(")");
}
System.out.println(sb.toString());
}
}
输出:
4.模拟斗地主洗牌、发牌、看牌
方法一:
分析:
分析:
* 1:创建一副牌
* 1.1 : 创建一个牌盒
* 1.2: 装牌
* 2:洗牌
* 3:发牌
* 4:看牌
package com.neuedu.collection;
import java.util.ArrayList;
import java.util.Collections;
public class PokerDemo {
public static void main(String[] args) {
ArrayList<String> poker = new ArrayList<>();
String[] colors = {"","","",""};
String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(String color : colors) {
for(String number : numbers) {
poker.add(color.concat(number));
}
}
poker.add("大王");
poker.add("小王");
//洗牌
Collections.shuffle(poker);
//创建打牌的人
ArrayList<String> rulai = new ArrayList<>();
ArrayList<String> sunwukong = new ArrayList<>();
ArrayList<String> weiwei = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>();
//摸牌
for(int i = 0; i < poker.size(); i++) {
if(i >= poker.size() - 3) {
dipai.add(poker.get(i));
}
if(i % 3 == 0) {
rulai.add(poker.get(i));
}
if(i % 3 == 1) {
sunwukong.add(poker.get(i));
}
if(i % 3 == 2) {
weiwei.add(poker.get(i));
}
}
//看牌
lookPoker("A", rulai);
lookPoker("B", sunwukong);
lookPoker("C", weiwei);
lookPoker("底牌", dipai);
}
public static void lookPoker(String name, ArrayList<String> pai) {
System.out.println(name + "的牌是:");
for(String s : pai) {
System.out.print(s + " ");
}
System.out.println();
}
}
输出:
方法二:
思路:
* 1:创建一个HashMap集合
* 2:创建一个ArrayList,用来存放牌的编号
* 3:创建花色数组和点数数组
* 4:从1编号开始向Hashmap中存放相应的编号和对应的牌,同时往ArrayList中存储编号
* 5:洗牌(洗的是编号)
* 6:发牌(发牌发的也是编号,为了保证编号是排序的,应该创建一个TreeSet集合)
* 7:看牌(遍历TreeSet,获取编号,然后从HashMap中找到对应的牌)
package com.neuedu.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* 4: 模拟斗地主洗牌、发牌和看牌
* 思路:
* 1:创建一个HashMap集合
* 2:创建一个ArrayList,用来存放牌的编号
* 3:创建花色数组和点数数组
* 4:从1编号开始向Hashmap中存放相应的编号和对应的牌,同时往ArrayList中存储编号
* 5:洗牌(洗的是编号)
* 6:发牌(发牌发的也是编号,为了保证编号是排序的,应该创建一个TreeSet集合)
* 7:看牌(遍历TreeSet,获取编号,然后从HashMap中找到对应的牌)
*
*/
public class PokerDemo2 {
public static void main(String[] args) {
Map<Integer,String> poker = new HashMap<>();
List<Integer> num = new ArrayList<>();
String[] colors = {"","","",""};
String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
int count = 1;
for(String number : numbers) {
for(String c : colors) {
poker.put(count, c.concat(number));
num.add(count);
count++;
}
}
poker.put(count, "小王");
num.add(count);
count++;
poker.put(count, "大王");
num.add(count);
//洗牌
Collections.shuffle(num);
TreeSet<Integer> linQingXia = new TreeSet<>();
TreeSet<Integer> zhouRunFa = new TreeSet<>();
TreeSet<Integer> liuDeHua = new TreeSet<>();
TreeSet<Integer> diPai = new TreeSet<>();
for(int i = 0; i <num.size(); i++) {
if(i >= num.size() - 3) {
diPai.add(num.get(i));
continue;
}
if(i % 3 == 0) {
linQingXia.add(num.get(i));
}
if(i % 3 == 1) {
zhouRunFa.add(num.get(i));
}
if(i % 3 == 2) {
liuDeHua.add(num.get(i));
}
}
//看牌
lookPoker("A", linQingXia, poker);
lookPoker("B", zhouRunFa, poker);
lookPoker("C", liuDeHua, poker);
lookPoker("底牌", diPai, poker);
}
public static void lookPoker(String name,Set<Integer> set,Map<Integer, String> map) {
System.out.println(name + "的牌是:");
for(Integer key : set) {
System.out.print(map.get(key) + " ");
}
System.out.println();
}
}
输出: