List基础与难度题

发布于:2025-04-17 ⋅ 阅读:(33) ⋅ 点赞:(0)

1. 向 ArrayList 中添加元素并打印

  • 功能描述
    • 程序创建一个空的 ArrayList 集合,用于存储字符串类型的元素。
    • 向该 ArrayList 中依次添加指定的字符串元素。
    • 使用增强型 for 循环遍历 ArrayList 中的所有元素,并将每个元素打印输出到控制台。
  • 测试数据描述
    • 预期向 ArrayList 中添加的字符串元素为 "apple""banana""cherry"
    • 预期控制台输出为:
import java.util.ArrayList;
import java.util.List;

public class ArrayListAdd {
    public static void main(String[] args) {
        List fruit = new ArrayList();
        String fruit1 = "apple";
        String fruit2 = "banana";
        String fruit3 = "cherry";

        fruit.add(fruit1);
        fruit.add(fruit2);
        fruit.add(fruit3);

        for (Object fruitNum : fruit) {
            System.out.println(fruitNum);
        }
    }
}

2. 从 HashSet 中移除重复元素

  • 功能描述
    • 首先创建一个 ArrayList 并向其中添加包含重复元素的字符串。
    • 然后利用 HashSet 的特性(HashSet 不允许存储重复元素),将 ArrayList 中的元素添加到 HashSet 中,自动去除重复元素。
    • 最后遍历 HashSet 并将其中的元素打印到控制台,验证重复元素已被成功移除。
  • 测试数据描述
    • ArrayList 中添加的字符串元素为 "apple""banana""apple",其中 "apple" 为重复元素。
    • 预期 HashSet 中存储的元素为 "apple""banana"(元素顺序可能不同,因为 HashSet 是无序的)。
    • 预期控制台输出类似(元素顺序不固定):

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class HashSetRemove {
    public static void main(String[] args) {
        List fruit = new ArrayList();
        String fruit1 = "apple";
        String fruit2 = "banana";
        String fruit3 = "apple";
        String fruit4 = "apple";

        fruit.add(fruit1);
        fruit.add(fruit2);
        fruit.add(fruit3);
        fruit.add(fruit4);

        for (Object fruitNum : fruit) {
            System.out.println(fruitNum);
        }

        System.out.println("====================");

        Set fruitNew = new HashSet();

        for (Object fruitNum : fruit) {
            fruitNew.add(fruitNum);
        }

        System.out.println(fruitNew);
    }
}

3. 使用 HashMap 统计单词出现次数

  • 功能描述
    • 给定一个字符串数组,程序创建一个 HashMap 用于统计每个单词在数组中出现的次数。
    • 遍历字符串数组,对于每个单词,在 HashMap 中检查该单词是否已存在。如果存在,则将其对应的值加 1;如果不存在,则将该单词作为键,值设为 1 存入 HashMap
    • 最后遍历 HashMap 的键值对,将每个单词及其出现的次数打印到控制台。
  • 测试数据描述
    • 给定的字符串数组为 {"apple", "banana", "apple", "cherry", "banana", "apple"}
    • 预期 HashMap 中的统计结果为:"apple" -> 3"banana" -> 2"cherry" -> 1
    • 预期控制台输出类似(顺序不固定):
import java.util.HashMap;
import java.util.Map;

public class HashMap_collection {
    public static void main(String[] args) {
        String [] fruits = {"apple", "banana", "apple", "cherry", "banana", "apple"};

        Map<String,Integer> fruitMap = new HashMap<>();

        for (String fruit : fruits) {
            if (fruitMap.containsKey(fruit)) {
                // 如果单词已存在于 HashMap 中,将其对应的值加 1
                fruitMap.put(fruit, fruitMap.get(fruit) + 1);
            } else {
                // 如果单词不存在于 HashMap 中,将该单词作为键,值设为 1 存入 HashMap
                fruitMap.put(fruit, 1);
            }
        }

//        int j = 0;
//        int k = 0;
//        int z = 0;
//        for (int i=0; i < fruit.length; i++) {
//            if (fruit[i].equals("apple")){
//                fruitMap.put("apple",j+=1);
//            }else if (fruit[i].equals("banana")){
//                fruitMap.put("banana",k+=1);
//            }else if (fruit[i].equals("cherry")){
//                fruitMap.put("cherry",z+=1);
//            }
//        }

        System.out.println(fruitMap);
    }
}

 

4. 合并两个 HashMap

  • 功能描述
    • 分别创建两个 HashMap,用于存储字符串类型的键和整数类型的值。
    • 将第一个 HashMap 的内容复制到一个新的 HashMap 中作为合并的基础。
    • 遍历第二个 HashMap 的键值对,对于每个键,如果在新的 HashMap 中已存在该键,则将对应的值相加;如果不存在,则将该键值对直接存入新的 HashMap
    • 最后遍历合并后的 HashMap,将每个键及其对应的值打印到控制台。
  • 测试数据描述
    • 第一个 HashMapmap1)的键值对为 {"apple" -> 3, "banana" -> 2}
    • 第二个 HashMapmap2)的键值对为 {"apple" -> 2, "cherry" -> 1}
    • 预期合并后的 HashMap 键值对为 {"apple" -> 5, "banana" -> 2, "cherry" -> 1}
    • 预期控制台输出类似(顺序不固定):
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMap_combine {
    public static void main(String[] args) {
        Map<String,Integer> fruitMap1 = new HashMap<>();
        Map<String,Integer> fruitMap2 = new HashMap<>();
        Map<String,Integer> fruitMap3 = new HashMap<>();

        fruitMap1.put("apple",3);
        fruitMap1.put("banana",2);
        fruitMap2.put("apple",2);
        fruitMap2.put("cherry",1);

        Iterator it = fruitMap1.keySet().iterator();
        while(it.hasNext()){
            String fruitKey = (String) it.next();
            fruitMap3.put(fruitKey,fruitMap1.get(fruitKey));
        }

        System.out.println("map1:"+fruitMap1);
        System.out.println("map2:"+fruitMap2);
        System.out.println("map3:"+fruitMap3);

        Iterator it1 = fruitMap2.keySet().iterator();
        while(it1.hasNext()){
            String fruitKey1 = (String) it1.next();
            if (fruitMap3.containsKey(fruitKey1)){
                fruitMap3.put(fruitKey1,fruitMap3.get(fruitKey1)+fruitMap2.get(fruitKey1));
            }else {
                fruitMap3.put(fruitKey1, fruitMap2.get(fruitKey1));
            }
        }

        System.out.println(fruitMap3);
    }

}

 

5. 实现一个简单的图书管理系统

  • 功能描述
    • 定义一个 Book 类,用于表示图书,包含图书的标题和作者属性。
    • 定义一个 Library 类,包含一个用于存储 Book 对象的 ArrayListLibrary 类提供以下方法:
      • addBook(Book book):向图书馆的图书列表中添加一本图书。
      • removeBook(Book book):从图书馆的图书列表中移除一本图书。
      • findBook(String title):根据图书标题在图书馆的图书列表中查找图书,如果找到则返回对应的 Book 对象,否则返回 null
      • displayAllBooks():遍历图书馆的图书列表,将每本图书的信息(标题和作者)打印到控制台。
    • 在 LibrarySystem 类的 main 方法中,进行以下操作:
      • 创建一个 Library 对象。
      • 向图书馆中添加几本图书。
      • 显示图书馆中所有的图书信息。
      • 根据图书标题查找一本图书,并显示查找结果。
      • 从图书馆中移除找到的图书,然后再次显示图书馆中所有的图书信息,验证图书已被成功移除。
  • 测试数据描述
    • 预期添加到图书馆的图书为:
      • 第一本图书:标题为 "Java Programming",作者为 "John Doe"
      • 第二本图书:标题为 "Python Crash Course",作者为 "Jane Smith"
    • 预期第一次显示所有图书时,控制台输出为:
Title: Java Programming, Author: John Doe
Title: Python Crash Course, Author: Jane Smith
  • 预期查找图书 "Java Programming" 时,能找到对应的 Book 对象。
  • 预期移除找到的图书后,再次显示所有图书时,控制台输出为:
Title: Python Crash Course, Author: Jane Smith

 Book类

public class Book {
    private String title;
    private String Author;

    public Book() {
    }

    public Book(String title, String author) {
        this.title=title;
        Author=author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title=title;
    }

    public String getAuthor() {
        return Author;
    }

    public void setAuthor(String author) {
        Author=author;
    }
}

Library类

import java.util.ArrayList;
import java.util.HashMap;


public class Library {
    //ArrayList
    private ArrayList<Book> books;

    public Library() {
        this.books = new ArrayList<>();
    }

    public void addBook(Book book){
        books.add(book);
    }

    public void removeBook(Book book){
        books.remove(book);
    }

    public Book findBook(String title){
        for (Book book : books) {
            if (book.getTitle().equals(title)){
                return book;
            }
        }
        return null;
    }

    public void displayAllBooks(){
        for (Book book : books) {
            System.out.println("Title:"+book.getTitle()+",Author:"+book.getAuthor());
        }
    }

//    //HashMap
//    private HashMap<String, Book> books;
//
//    public Library() {
//        this.books = new HashMap<>();
//    }
//
//    public void addBook(Book book) {
//        books.put(book.getTitle(), book);
//    }
//
//    public void removeBook(Book book) {
//        books.remove(book.getTitle());
//    }
//
//    public Book findBook(String title) {
//        return books.get(title);
//    }
//
//    public void displayAllBooks() {
//        for (Book book : books.values()) {
//            System.out.println(book);
//        }
//    }
}

Test类

public class test {
    public static void main(String[] args) {
        Library library = new Library();

        Book book1 = new Book("Java Programming", "John Doe");
        Book book2 = new Book("Python Crash Course", "Jane Smith");

        library.addBook(book1);
        library.addBook(book2);

        System.out.println("所有图书信息:");
        library.displayAllBooks();

        Book foundBook = library.findBook("Java Programming");
        if (foundBook != null) {
            System.out.println("找到图书:Title: " + foundBook.getTitle() + ", Author: " + foundBook.getAuthor());
        } else {
            System.out.println("未找到该图书。");
        }

        System.out.println("\n移除找到的书籍");
        library.removeBook(foundBook);

        System.out.println("\n移除图书后所有图书信息:");
        library.displayAllBooks();
    }
}

难度题目

在线商城订单管理系统

功能描述

此在线商城订单管理系统是一个较为复杂的面向对象程序,用于模拟在线商城的订单管理流程,包含了商品、用户、购物车、订单等核心概念。以下是各个类的详细功能:

1. Product 
  • 属性
    • productId:商品的唯一标识符,类型为 String
    • name:商品的名称,类型为 String
    • price:商品的单价,类型为 double
    • stock:商品的库存数量,类型为 int
  • 方法
    • 构造方法:用于初始化商品的基本信息。
    • getProductId():获取商品的唯一标识符。
    • getName():获取商品的名称。
    • getPrice():获取商品的单价。
    • getStock():获取商品的库存数量。
    • decreaseStock(int quantity):减少商品的库存数量,当减少的数量大于当前库存时,抛出异常。
    • increaseStock(int quantity):增加商品的库存数量。
2. User 
  • 属性
    • userId:用户的唯一标识符,类型为 String
    • name:用户的姓名,类型为 String
    • shoppingCart:用户的购物车,类型为 ShoppingCart
    • orders:用户的订单列表,类型为 List<Order>
  • 方法
    • 构造方法:用于初始化用户的基本信息,并创建一个空的购物车和订单列表。
    • getUserId():获取用户的唯一标识符。
    • getName():获取用户的姓名。
    • getShoppingCart():获取用户的购物车。
    • getOrders():获取用户的订单列表。
    • addOrder(Order order):将一个新的订单添加到用户的订单列表中。
3. ShoppingCart 
  • 属性
    • items:购物车中的商品项列表,类型为 List<CartItem>
  • 方法
    • 构造方法:用于创建一个空的购物车。
    • addItem(Product product, int quantity):向购物车中添加一个商品项,如果商品已存在,则增加其数量;如果商品不存在,则创建一个新的商品项。
    • removeItem(Product product):从购物车中移除指定的商品项。
    • updateQuantity(Product product, int newQuantity):更新购物车中指定商品项的数量。
    • getTotalPrice():计算购物车中所有商品项的总价。
    • clear():清空购物车中的所有商品项。
4. CartItem 
  • 属性
    • product:购物车中的商品,类型为 Product
    • quantity:商品的数量,类型为 int
  • 方法
    • 构造方法:用于初始化购物车中的商品项。
    • getProduct():获取购物车中的商品。
    • getQuantity():获取商品的数量。
    • getTotalPrice():计算该商品项的总价。
5. Order 
  • 属性
    • orderId:订单的唯一标识符,类型为 String
    • user:下单的用户,类型为 User
    • items:订单中的商品项列表,类型为 List<CartItem>
    • orderStatus:订单的状态,类型为 String(如 "待支付"、"已支付"、"已发货" 等)。
  • 方法
    • 构造方法:用于初始化订单的基本信息。
    • getOrderId():获取订单的唯一标识符。
    • getUser():获取下单的用户。
    • getItems():获取订单中的商品项列表。
    • getOrderStatus():获取订单的状态。
    • setOrderStatus(String status):设置订单的状态。
    • getTotalPrice():计算订单中所有商品项的总价。
6. OnlineMall 
  • 属性
    • products:商城中的商品列表,类型为 List<Product>
    • users:商城的用户列表,类型为 List<User>
  • 方法
    • 构造方法:用于创建一个空的商城,包含空的商品列表和用户列表。
    • addProduct(Product product):向商城中添加一个新的商品。
    • addUser(User user):向商城中添加一个新的用户。
    • processOrder(User user):处理用户的订单,包括创建订单、减少商品库存、清空购物车等操作。

测试数据描述
  • 商品数据
    • 笔记本电脑:商品编号 "P001",名称 "笔记本电脑",单价 5000 元,库存 10 件。
    • 手机:商品编号 "P002",名称 "手机",单价 3000 元,库存 20 件。
  • 用户数据
    • 用户 "张三":用户编号 "U001"
  • 购物车数据
    • 用户 "张三" 的购物车中添加 1 台笔记本电脑和 2 部手机。
  • 预期结果
    • 生成一个新的订单,订单编号为以 "O" 开头并包含当前时间戳的字符串。
    • 订单总价为 1 * 5000 + 2 * 3000 = 11000 元。
    • 订单状态初始为 "待支付"
    • 笔记本电脑的库存减少为 9 件,手机的库存减少为 18 件。
    • 用户 "张三" 的购物车被清空。

Product类

public class Product {
    private String productId;
    private String name;
    private double price;
    private int stock;

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

    public String getProductId() {
        return productId;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public void decreaseStock(int quantity) {
        if (quantity > stock) {
            throw new IllegalArgumentException("库存不足");
        }
        stock -= quantity;
    }

    public void increaseStock(int quantity) {
        stock += quantity;
    }
}

User类

import java.util.ArrayList;
import java.util.List;

public class User {
    private String userId;
    private String name;
    private ShoppingCart shoppingCart;
    private List<Order> orders;

    public User(String userId, String name) {
        this.userId = userId;
        this.name = name;
        this.shoppingCart = new ShoppingCart();
        this.orders = new ArrayList<>();
    }

    public String getUserId() {
        return userId;
    }

    public String getName() {
        return name;
    }

    public ShoppingCart getShoppingCart() {
        return shoppingCart;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public void addOrder(Order order) {
        orders.add(order);
    }
}

ShoppingCart类

import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {
    private List<CartItem> items;

    public ShoppingCart() {
        this.items = new ArrayList<>();
    }

    public void addItem(Product product, int quantity) {
        for (CartItem item : items) {
            if (item.getProduct().getProductId().equals(product.getProductId())) {
                item.setQuantity(item.getQuantity() + quantity);
                return;
            }
        }
        items.add(new CartItem(product, quantity));
    }

    public void removeItem(Product product) {
        items.removeIf(item -> item.getProduct().getProductId().equals(product.getProductId()));
    }

    public void updateQuantity(Product product, int newQuantity) {
        for (CartItem item : items) {
            if (item.getProduct().getProductId().equals(product.getProductId())) {
                item.setQuantity(newQuantity);
                return;
            }
        }
    }

    public double getTotalPrice() {
        double total = 0;
        for (CartItem item : items) {
            total += item.getTotalPrice();
        }
        return total;
    }

    public void clear() {
        items.clear();
    }

    public List<CartItem> getItems() {
        return items;
    }
}

CartItem类

public class CartItem {
    private Product product;
    private int quantity;

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

    public Product getProduct() {
        return product;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity=quantity;
    }

    public double getTotalPrice() {
        return product.getPrice() * quantity;
    }
}

Order类

public class Order {
    private String orderId;
    private User user;
    private List<CartItem> items;
    private String orderStatus;

    public Order(String orderId, User user, List<CartItem> items, String orderStatus) {
        this.orderId = orderId;
        this.user = user;
        this.items = items;
        this.orderStatus = orderStatus;
    }

    public String getOrderId() {
        return orderId;
    }

    public User getUser() {
        return user;
    }

    public List<CartItem> getItems() {
        return items;
    }

    public String getOrderStatus() {
        return orderStatus;
    }

    public void setOrderStatus(String status) {
        this.orderStatus = status;
    }

    public double getTotalPrice() {
        double total = 0;
        for (CartItem item : items) {
            total += item.getTotalPrice();
        }
        return total;
    }
}

OnlineMall类

import java.util.ArrayList;
import java.util.List;

public class OnlineMall {
    private List<Product> products;
    private List<User> users;

    public OnlineMall() {
        this.products = new ArrayList<>();
        this.users = new ArrayList<>();
    }

    public void addProduct(Product product) {
        products.add(product);
    }

    public void addUser(User user) {
        users.add(user);
    }

    public void processOrder(User user) throws Exception {
        ShoppingCart cart = user.getShoppingCart();
        List<CartItem> items = new ArrayList<>(cart.getItems());
        for (CartItem item : items) {
            Product product = item.getProduct();
            product.decreaseStock(item.getQuantity());
        }
        String orderId = "O" + System.currentTimeMillis();
        Order order = new Order(orderId, user, items, "待支付");
        user.addOrder(order);
        cart.clear();
    }
}

Test类

public class test {
    public static void main(String[] args) throws Exception {
        OnlineMall mall = new OnlineMall();
        Product laptop = new Product("P001", "笔记本电脑", 5000, 10);
        Product phone = new Product("P002", "手机", 3000, 20);
        mall.addProduct(laptop);
        mall.addProduct(phone);

        User zhangsan = new User("U001", "张三");
        mall.addUser(zhangsan);

        ShoppingCart cart = zhangsan.getShoppingCart();
        cart.addItem(laptop, 1);
        cart.addItem(phone, 2);

        mall.processOrder(zhangsan);

        System.out.println("订单编号: " + zhangsan.getOrders().get(0).getOrderId());
        System.out.println("订单总价: " + zhangsan.getOrders().get(0).getTotalPrice());
        System.out.println("订单状态: " + zhangsan.getOrders().get(0).getOrderStatus());
        System.out.println("笔记本电脑库存: " + laptop.getStock());
        System.out.println("手机库存: " + phone.getStock());
        System.out.println("购物车是否为空: " + zhangsan.getShoppingCart().getItems().isEmpty());
    }
}