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

如何在Java的LinkedList中交换两个随机字符串?

在Java LinkedList中交换字符串元素的方法

其实交换LinkedList中的字符串和整数元素逻辑完全一致,因为LinkedList存储的是对象引用,交换操作不依赖元素的具体类型。下面给你两种可行的实现方式,结合你的现有代码进行扩展:

方法1:使用LinkedList的swap方法(Java 21+)

Java 21为LinkedList新增了swap(int i, int j)方法,可以直接交换两个索引位置的元素,代码更简洁:

import java.util.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> ll = new LinkedList<>();
        Scanner sc = new Scanner(System.in); 
        System.out.println("enter total count of elements -> ");
        int num = Integer.parseInt(sc.next());

        while(num>0) {
            ll.add(sc.next());
            num--; 
        }

        // 输入要交换的两个索引
        System.out.println("请输入第一个要交换的元素索引:");
        int index1 = sc.nextInt();
        System.out.println("请输入第二个要交换的元素索引:");
        int index2 = sc.nextInt();

        try {
            // 直接调用swap方法交换
            ll.swap(index1, index2);
            System.out.println("交换后的LinkedList:" + ll);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("输入的索引超出范围,请重新输入!");
        }

        sc.close();
    }
}

方法2:手动实现交换(兼容所有Java版本)

如果你的Java版本低于21,可以通过get和set方法手动完成交换:

import java.util.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> ll = new LinkedList<>();
        Scanner sc = new Scanner(System.in); 
        System.out.println("enter total count of elements -> ");
        int num = Integer.parseInt(sc.next());

        while(num>0) {
            ll.add(sc.next());
            num--; 
        }

        // 输入要交换的两个索引
        System.out.println("请输入第一个要交换的元素索引:");
        int index1 = sc.nextInt();
        System.out.println("请输入第二个要交换的元素索引:");
        int index2 = sc.nextInt();

        try {
            // 获取两个位置的元素并交换
            String temp = ll.get(index1);
            ll.set(index1, ll.get(index2));
            ll.set(index2, temp);
            System.out.println("交换后的LinkedList:" + ll);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("输入的索引超出范围,请重新输入!");
        }

        sc.close();
    }
}

关键说明

  • 不管是字符串还是整数,交换逻辑都是操作LinkedList中对应索引的对象引用,所以本质没有区别,不需要特殊处理字符串。
  • 必须注意索引的合法性:索引范围是0到ll.size()-1,超出这个范围会抛出IndexOutOfBoundsException,建议加上异常捕获处理。

内容的提问来源于stack exchange,提问作者Назар Зайчиков

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:15:36