且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串数组转换为列表:双括号

更新时间:2023-11-15 15:56:04

您不必要地转换了返回的列表转换为其原始的 String 表示形式,将该 String 拆分为一个 String [] ,然后将 String [] 转换为List。

You're unnecessarily converting the returned List to its raw String representation, splitting that String into a String[], then converting the String[] to List.

相反,直接使用

package com.example.list;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListExample {
    static List<String> strlist = new ArrayList<String>();

    public static void main(String[] args) {
        List<String> strlisttemp = new ArrayList<String>();
        strlisttemp.add("a");
        strlisttemp.add("b");
        strlisttemp.add("c");

        final JList list = new JList(strlisttemp.toArray());
        list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        final ListSelectionListener listSelectionListener = new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {

                strlist = list.getSelectedValuesList(); // use this instead

//              String lstr = list.getSelectedValuesList().toString();
//              strlist = Arrays.asList(lstr.split("\\s*,\\s*"));

                System.out.println(strlist);
            }
        };

        list.addListSelectionListener(listSelectionListener);
        JOptionPane.showMessageDialog(null, list, "Select", JOptionPane.QUESTION_MESSAGE);


    }
}