You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何将ArrayDeque元素按奇偶拆分到两个ArrayList

Java集合队列作业修正方案

作业要求核对

  • 字符串生成逻辑必须放在main方法内:创建ArrayDeque队列,存入50个字符串,每个字符串为字符'a'随机重复1-50次的结果
  • 队列生成完成后传入executeTasks方法,方法内仅做拆分逻辑:将字符串按'a'个数的奇偶性,分别存入even(偶数)、odd(奇数)两个ArrayList集合

原代码问题点

  • 职责错位:随机字符串生成逻辑错误写在executeTasks方法内部,main方法仅存入1个无关的测试字符串
  • 逻辑冗余:executeTasks内多了一层无意义的50次循环,和队列传入的任务完全脱节
  • 类型错误:随机次数计算时错误强转为char类型,会导致计数异常

修正后完整代码

import java.util.*;

class TaskManager {
    List<String> executedTasks;
    List<String> even;
    List<String> odd;

    // 构造方法初始化集合
    public TaskManager() {
        executedTasks = new ArrayList<>();
        even = new ArrayList<>();
        odd = new ArrayList<>();
    }

    // 仅处理队列拆分逻辑,不生成字符串
    public void executeTasks(Deque<String> theQueue) {
        while (theQueue.size() > 0) {
            String theTask = theQueue.poll();
            System.out.println("Processing the task: " + theTask);
            
            // 按字符串长度判断奇偶,拆分到对应列表
            if (theTask.length() % 2 == 0) {
                even.add(theTask);
            } else {
                odd.add(theTask);
            }
            
            executedTasks.add(theTask);
            System.out.println("\nExecuted total " + executedTasks.size() + " tasks\n");
        }
    }
}

public class QueuesAndLoops {
    public static void main(String[] args) throws java.lang.Exception {
        Deque<String> taskQueue1 = new ArrayDeque<>();
        char targetChar = 'a';
        
        // 在main方法内完成50个随机字符串生成并入队
        for (int n = 0; n < 50; n++) {
            // 生成1-50的随机重复次数
            int repeatCount = (int)(Math.random() * 50 + 1);
            StringBuilder taskStr = new StringBuilder();
            for (int i = 0; i < repeatCount; i++) {
                taskStr.append(targetChar);
            }
            taskQueue1.offer(taskStr.toString());
        }

        TaskManager taskExecutor = new TaskManager();
        // 传入生成好的队列处理
        taskExecutor.executeTasks(taskQueue1);
        
        // 输出结果
        System.out.println("偶数长度(a的个数为偶数)字符串:");
        System.out.println(taskExecutor.even);
        System.out.println("奇数长度(a的个数为奇数)字符串:");
        System.out.println(taskExecutor.odd);
    }
}

逻辑说明

  • Java中对象作为参数传入方法时是引用传递,方法内取出队列元素的操作会直接作用于传入的队列对象,处理完成后原队列会被清空
  • 字符串长度和'a'的个数完全相等,直接判断length()的奇偶即可,不需要额外遍历计数
  • 字符串拼接推荐使用StringBuilder,比直接用+=拼接效率更高,尤其是循环次数较多的场景

内容的提问来源于stack exchange,提问作者EurekaII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 09:18:27