JavaSEDemo26集合与垃圾回收机制

练习题

练习1

题目
请使用LinkedList来模拟一个堆栈或者队列数据结构。
答案
堆栈

import java.util.LinkedList;

public class MyStack<E> {
    private LinkedList<E> list=new LinkedList<>();

    public LinkedList<E> getList() {
        return list;
    }

    public void setList(LinkedList<E> list) {
        this.list = list;
    }
    public void push(E e){
        this.list.addFirst(e);
    }
    public E pop(){
        return this.list.pollFirst();
    }

    @Override
    public String toString() {
        return "MyStack{" +
                "list=" + list +
                '}';
    }
    public static void main(String[] args){
        MyStack<String> myStack = new MyStack<>();
        myStack.push("刘备");
        myStack.push("关羽");
        myStack.push("张飞");
        System.out.println("myStack = " + myStack);
        System.out.println("myStack.pop() = " + myStack.pop());
        System.out.println("myStack = " + myStack);
    }
}

队列

import java.util.LinkedList;

public class Queue<E> {
   private LinkedList<E> list = new LinkedList<>();

   public LinkedList<E> getList() {
      return list;
   }

   public void setList(LinkedList<E> list) {
      this.list = list;
   }
    public void add(E e){
       list.addLast(e);
    }
    public E poll() {
       return list.pollFirst();
   }

   @Override
   public String toString() {
      return "Stack [list=" + list + "]";
   }
    public static void main(String[] args){
      Queue<String> stack = new Queue<>();
      stack.add("刘东月");
      stack.add("徐培杰");
      stack.add("刘博");
      System.out.println(stack);
      System.out.println("---------");
      System.out.println(stack.poll());
      System.out.println(stack);
      System.out.println("---------");
      System.out.println(stack.poll());
      System.out.println(stack);
    }
}

练习2

题目:
用TreeSet存储以下数据:
“xiaoqiang”、 “zhangsan”、“lisi”、“xiaohua”、 “ruhua”、 “wangcai”
要求按照字符串的长度进行排序后再存储(如果长度相同,则按字符串的自然顺序排序)
答案:

@Test
public void test1() {
    TreeSet<String> set = new TreeSet<>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            int i = o1.length() - o2.length();
            int j = o1.compareTo(o2);
            return i==0?j:i;
        }
    });
    set.add("xiaoqiang");
    set.add("zhangsan");
    set.add("lisi");
    set.add("xiaohua");
    set.add("ruhua");
    set.add("wangcai");
    System.out.println("set = " + set);
}

练习3

题目
List对象中存放多个Person对象(此对象包含,名字,年龄、id)。按Person的年龄从小到大排序,假设年龄相等的话再按名字的大小来排序。求出年龄最大的那个学生信息。
答案

public class Person {
    private int id;
    private String name;
    private int age;

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Test {
    public static void main(String[] args){
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person(1,"tom",20));
        list.add(new Person(2,"aom",20));
        list.add(new Person(3,"bom",18));
       /* Collections.sort(list, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int i = o1.getAge() - o2.getAge();
                int j = o1.getName().compareTo(o2.getName());
                return i==0?j:i;
            }
        });*/
        list.sort(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int i = o1.getAge() - o2.getAge();
                int j = o1.getName().compareTo(o2.getName());
                return i==0?j:i;
            }
        });
        System.out.println(list);
    }
}



练习4

题目
“chenhao”
“zhangsan”
“zhangsan”
“chenhao”
“lisi”
“wangwu”
“zhaoliu”
“xiaoqiang”
“haha”
打印输出各个字符串出现的次数(使用HashMap实现,键保存字符串,值保存保存出现的次数)

public static void main(String[] args){
    String[] arr=new String[]{"chenhao","zhangsan","zhangsan","chenhao"
    ,"lisi","wangwu","zhaoliu","xiaoqiang","haha"};
    HashMap<String, Integer> map = new HashMap<>();
    for (String s : arr) {
        Integer count = map.get(s);
        if (count==null){
            map.put(s,1);
        }else {
            map.put(s,map.get(s)+1);
        }
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey()+"="+entry.getValue());
    }
}

练习5

题目
“asdascveasrgdfsdf”获取该字符串中,每一个字母出现的次数。
要求:打印结果是:a(2)b(1)…
答案

@Test
public void test2() {
    char[] chars = "asdascveasrgdfsdf".toCharArray();
    TreeMap<Character, Integer> map = new TreeMap<>();
    for (char c : chars) {
        Integer count = map.get(c);
        if (count==null){
            map.put(c,1);
        }else{
            map.put(c,map.get(c)+1);
        }
    }
    for (Map.Entry<Character, Integer> entry : map.entrySet()) {
        System.out.print(entry.getKey() +"("+ entry.getValue()+")");
    }
}

练习6

题目
随机产生50个30到35的整数,统计每个数字出现的次数(TreeMap实现),输出时按照数字的降序排列,并且统计出现次数最多的数字和它的次数。
PS:如果有两个数字出现的次数一样,则只需输出其中一个。
答案

@Test
public void test1() {
    Random random = new Random();
    TreeMap<Integer, Integer> map = new TreeMap<>(new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
 });
    for (int i = 0; i < 50; i++) {
        int n = random.nextInt(6) + 30;
        Integer count = map.get(n);
        if (count==null){
            map.put(n,1);
        }else{
            map.put(n,count+1);
        }
    }
    Integer maxKey=0;
    Integer maxValue=0;
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey()+":"+entry.getValue());
        if (entry.getValue()>maxValue){
            maxValue=entry.getValue();
            maxKey=entry.getKey();
        }
    }
    System.out.println("出现次数最多的数是:"+maxKey+",出现了"+maxValue+"次");

}

练习7

题目
创建购物车实体类,模拟购物车功能需求:

  1. 添加商品到购物车(输入商品的编号和数量)
  2. 删除商品(删除购物车中的指定购物项)
  3. 修改商品(修改商品的数量)
  4. 显示所购买的商品信息(按购买商品的总价进行升序显示)
    答案

Product类

public class Product {
    private int  id;
    private String name;// 名称
    private int count;//数量
 private double price;//单价

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Product() {
    }

    public Product(int id, String name, int count) {
        this.id = id;
        this.name = name;
        this.count = count;
    }

    public Product(int id, String name, int count, double price) {
this.id = id;
        this.name = name;
        this.count = count;
        this.price = price;
    }

    @Override
    public String toString() {
        return id+"----"+name+"----"+count;
    }
}

Cart类

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Cart {
    private Map<Integer, CartItem> map=new HashMap<>();
    private double total;

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    //得到购物车的集合
    public Collection<CartItem> getCartItems(){
        return map.values();
    }
    //添加购物车
    public void add(CartItem cartItem){
        Product product = cartItem.getProduct();//得到购买的商品对象
        int id = product.getId();//得到商品的id
        //到map取得 id对应的购物项
        CartItem cartItem1 = map.get(id);
       if (cartItem1!=null){//原来买过
           cartItem1.setCount(cartItem1.getCount()+cartItem.getCount());//原来的count+新买的count
       }
       else {//原来没买过
            map.put(id,cartItem);//直接往里放
        }
       setTotal(total+cartItem.getSubTotal());//原来的总价+新购物的小计
    }
    //删除购物车
    public void remove(Integer id){
        CartItem cartItem = map.remove(id);
        setTotal(total-cartItem.getSubTotal());//原来的总价-删除的购物项的小计
    }
    //清空购物车
    public void clear(){
        map.clear();
        setTotal(0);
    }

    public void update(int id, int count) {
        CartItem cartItem = map.get(id);
        if (cartItem!=null){
            setTotal(total-cartItem.getSubTotal());
            cartItem.setCount(count);
            setTotal(total+cartItem.getSubTotal());
        }
    }
}


CartItem类

public class CartItem {
    private Product product;//购买的商品
    private int count;//购买的数量
    private double subTotal;//小计

    @Override
    public String toString() {
        return  product.getId() +"\t"+product.getName()+"\t"+product.getPrice()+"\t"+count+"\t"+getSubTotal();
    }

    public CartItem(Product product, int count) {
        this.product = product;
        this.count = count;
    }
 public CartItem() {
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public double getSubTotal() {
        return product.getPrice()*count;
    }

    public void setSubTotal(double subTotal) {
        this.subTotal = subTotal;
    }
}

ProductNotEnoughException类

package a00;

public class ProductNotEnoughException extends Exception {
    public ProductNotEnoughException(String message) {
        super(message);
    }

    public ProductNotEnoughException() {
    }
}

ProductNotExistException类

public class ProductNotExistException extends Exception {
    public ProductNotExistException(String message) {
        super(message);
 }

    public ProductNotExistException() {
    }
}

Shop类

import java.util.Collection;

public class Shop {
    private Cart cart=new Cart();
    private Product[] products=new Product[]{
            new Product(1,"黄瓜",10,2),
            new Product(2,"西红柿",10,3),
            new Product(3,"菠萝",10,2),
            new Product(4,"苹果",10,5),
            new Product(5,"桔子",10,3),
    };
    public void buy(int id, int count) throws ProductNotExistException, ProductNotEnoughException {
        //遍历数组判断用户输入id在商品数组中,不存在抛异常:商品不存在
        boolean flag=false;
        for (Product product : products) {
            if (product.getId()==id){
                flag=true;
                break;
            }
        }
        if (flag==false){
            throw new ProductNotExistException("商品不存在");
        }
        //遍历数组判断商品数量是否<=库存的商品数量,如果抛出商品库存不够异常
        for (Product product : products) {
            if (product.getId()==id && count>product.getCount()){
                throw new ProductNotEnoughException("商品库存不够");
            }
        }
        //将数组对应的商品数量减购买数量
        for (Product product : products) {
            if (product.getId()==id ){
                product.setCount(product.getCount()-count);
                System.out.println("购买成功");
                //添加购物车的入口
  CartItem cartItem = new CartItem();
                cartItem.setProduct(product);
                cartItem.setCount(count);
                cart.add(cartItem);
                showCartList();
                break;
            }
        }
    }
    //show()显示商品列表
    public void show(){
        System.out.println("请选择商品序号:");
        for (Product product : products) {
            System.out.println(product);
        }
    }
    public void menu(){
        System.out.println("1.添加商品到购物车");
        System.out.println("2.删除商品");
        System.out.println("3.修改商品");
        System.out.println("4.查看购物车");
    }
    //show()显示购物车列表
    public void showCartList(){
       System.out.println("购物车列表:");
Collection<CartItem> cartItems = cart.getCartItems();
TreeSet<CartItem> set = new TreeSet<>(new Comparator<CartItem>() {
        @Override
        public int compare(CartItem o1, CartItem o2) {
            return Double.compare(o1.getSubTotal(),o2.getSubTotal());
        }
    });
    set.addAll(cartItems);
    System.out.println("id\tname\tprice\tcount\tsubtotal");
    for (CartItem cartItem : set) {
        System.out.println(cartItem);
}
System.out.println("总价格:"+cart.getTotal());
    }

    public void remove(int id) {
        cart.remove(id);
    }
 public void update(int id, int count) {
        cart.update(id,count);
    }
}

TestMain类

import java.util.Scanner;

public class TestMain {
    public static void main(String[] args) {
        //创建商店对象
        Shop shop = new Shop();
        //创建用户对象
        User user = new User(shop);
        //创建Scanner对象
        Scanner scanner = new Scanner(System.in);
        while (true){
            shop.menu();
            System.out.println("请输入功能编号:");
            int i = scanner.nextInt();
            switch(i){
                case 1:
                    shop.show();
                    System.out.println("请输入商品id:");
                    int id = scanner.nextInt();
                    System.out.println("请输入购买数量:");
                    int count = scanner.nextInt();
                    //调用user对象的buy()
                    user.buy(id,count);
                    shop.show();
                    break;
                case 2:
                    System.out.println("请输入商品id:");
                    int id2 = scanner.nextInt();
                    shop.remove(id2);
                    break;
                case 3:
                     System.out.println("请输入商品id:");
                    id = scanner.nextInt();
                    System.out.println("请输入购买数量:");
                    count = scanner.nextInt();
                    shop.update(id,count);
                    break;
package a00;

import java.util.Scanner;

public class TestMain {
    public static void main(String[] args) {
        //创建商店对象
        Shop shop = new Shop();
        //创建用户对象
        User user = new User(shop);
        //创建Scanner对象
        Scanner scanner = new Scanner(System.in);
        while (true){
            shop.menu();
            System.out.println("请输入功能编号:");
            int i = scanner.nextInt();
            switch(i){
                case 1:
                    shop.show();
                    System.out.println("请输入商品id:");
                    int id = scanner.nextInt();
                    System.out.println("请输入购买数量:");
                    int count = scanner.nextInt();
                    //调用user对象的buy()
                    user.buy(id,count);
                    shop.show();
                    break;
                case 2:
                    System.out.println("请输入商品id:");
                    int id2 = scanner.nextInt();
                    shop.remove(id2);
                    break;
                case 3:
                     System.out.println("请输入商品id:");
                    id = scanner.nextInt();
                    System.out.println("请输入购买数量:");
                    count = scanner.nextInt();
                    shop.update(id,count);
                    break;
                case 4:
                    shop.showCartList();
                    break;
                default:
                    break;
            }


        }
    }
}


User类

public class User {
   private Shop shop;

    public User() {
    }

    public User(Shop shop) {
        this.shop = shop;
    }
    public void buy(int  id,int count){
        try {
            shop.buy(id,count);
        } catch (ProductNotExistException e) {
            System.out.println(e.getMessage());
        } catch (ProductNotEnoughException e) {
            System.out.println(e.getMessage());
        }
    }
}

Map

poolFirstEntry

移除并返回与此映射中的最小键关联的键-值映射关系;如果映射为空,
则返回 null。

pollLastEntry

移除并返回与此映射中的最大键关联的键-值映射关系;如果映射为空,
则返回 null。

subMap(K fromKey,boolean fromInclusive,K to Key,boolean toInclusive)

subMap(K fromKey,K toKey)

数组也能实现内部比较器和外部比较器

Arrays工具类

Arrays.sort()

Collections工具类

Collections.sort()

线程安全的集合版本

  • synchronizedCollection
  • synchronizedMap
  • synchronizedSortedMap
  • synchronizedSortedSet

集合总结

可以使用比较器的方法、类或接口

  • TreeMap
  • TreeSet
  • list.sort
  • Arrays.sort
  • Collections.sort

垃圾回收

1.什么是垃圾
2.什么是垃圾回收

如何定位垃圾
引用计数算法
可达性分析算法

垃圾回收算法
标记清除算法
复制算法
标记整理算法
分代收集算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香鱼嫩虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值