您的位置:首页 > 编程语言 > Java开发

Java复习笔记——Map运用(检测Random特性,多维集合,二叉树实现)

2017-08-09 16:03 309 查看

Map

使用Map来统计Random的特性,用键来表示某个数字,Value表示改值出现的次数

Random rand = new Random(47);
Map<Integer ,Integer> m = new HashMap<>();
for(int i =0;i<10000;i++){
int r =rand.nextInt(20);
Integer count = m.get(r);
m.put(r, count==null?1:count+1);
}
System.out.println(m);


使用Map实现多维集合,Value为 List、Set、Map

public class SortTest {

public static Map<Integer ,List<? extends Pet>> petPeople =new HashMap<>();

static {
petPeople.put(1,
Arrays.asList(new Pet("cat1"),new Pet("CAT2")));

petPeople.put(2,
Arrays.asList(new Pet("DOG1"),new Pet("DOG2"), new Pet("Dog3")));

petPeople.put(3,
Arrays.asList(new Pet("TIGR1"),new Pet("TIGR2")));

petPeople.put(4,
Arrays.asList(new Pet("Mouse1"),new Pet("Mouse2"),new Pet("Mouse3")));
}

public static void main(String[] args) {
System.out.println(petPeople.keySet());
System.out.println(petPeople.values());
for(Integer i :petPeople.keySet()){
for(Pet pet : petPeople.get(i)){
System.out.println(pet.name);
}

}


Arrays.asList(T...a) 将不固定参数内容 包装为一个List返回


二叉树的实现

public class BinaryTree {

private Node root;

public static void main(String[] args) {
// TODO Auto-generated method stub

BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(5);
bt.add(4);
bt.add(3);
bt.add(7);
bt.print();

}

public void add(int i) {
// TODO Auto-generated method stub
if (root == null) {
root = new Node(i);
} else {
root.addNode(i);
}

}

public void print() {
root.printNode();
}

}

class Node {

/**
* 创建节点,每个节点分别有左节点、有节点、内容
* 每个节点都有添加节点的方法,如果添加的内容大于 节点内容就放在右节点,反之放在左节点
*/
public Node left;
public int data;
public Node right;

public Node(int data) {
this.data = data;
}

/**
*
* @param i
*
* 如果添加的内容大于 节点内容就放在右节点,反之放在左节点
* 如果左节点为空就创建左节点,
* 如果不为空则调用addNode(),循环判断左右子节点是否为空
*/
public void addNode(int i) {

if (i > this.data) {
if (this.right == null) {
right = new Node(i);
} else {
right.addNode(i);
}
} else {
if (left == null) {
left = new Node(i);
} else {
left.addNode(i);
}
}
}

public void printNode() {

if (left != null) {

left.printNode();
}
System.out.println(data + "  ");

if (right != null) {
right.printNode();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 二叉树 random