集合笔试题
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 i