將兩個單獨的 Set 轉換為二維數組 (Convert two separate Sets to a 2D array)


問題描述

將兩個單獨的 Set 轉換為二維數組 (Convert two separate Sets to a 2D array)

I have two Sets of Strings, with each in the following format:

Set1(Names)  Set2(Sizes)

Pics         450 KB
Videos       50 MB
Music        32 MB

The two Sets are LinkedHashSets, so order is guaranteed. The Sets are also guaranteed to be the same size.

I need to show these two Sets in a JTable in the format above. Naturally, the simplest way to do it would be to create a 2D array, but I'm getting confused as to the order of each.

What is the best way to do it? Ideally, it would not require iteration through the Sets, but normally, the Sets' size is less than 10.


參考解法

方法 1:

You don't need to create a 2D array - see DefaultTableModel.addColumn.  So you can use:

JTable table = new JTable();
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addColumn("Names", s1.toArray(new String[0]));
model.addColumn("Sizes", s2.toArray(new String[0]));

Sorry if syntax is slightly off - not at an IDE right now.

方法 2:

Set<String> namesSet = ...;
Set<String> sizesSet = ...;
String[] names = namesSet.toArray(new String[namesSet.size()]);
String[] sizes = sizesSet.toArray(new String[sizesSet.size()]);
String[][] namesAndSizes = {names, sizes};

(by RedandwhiteNick Rippemsell)

參考文件

  1. Convert two separate Sets to a 2D array (CC BY-SA 3.0/4.0)

#java #collections #jtable #set #swing






相關問題

電子郵件地址中帶有 + 字符的 Java 郵件 (Java mail with + character in email address)

如何快速原型化 Java 代碼? (How to quickly prototype Java code?)

如何使用 Maven 在目標(SVN-)服務器上創建 Javadoc? (How to create Javadoc on the target (SVN-) server using Maven?)

為什麼檢查二叉樹有效性的解決方案不起作用? (Why the solution for checking the validity of binary tree is not working?)

Selenium webdriver通過第一個數字找到texy (Selenium webdriver find texy by first digits)

setOnClickListener 沒有在圖像視圖上被調用 (setOnClickListener is not getting called on image view)

繪製多邊形:找不到錯誤 (Drawing Polygon : unable to find error)

半透明 JButton:對像出現在背景中 (Semi-Transparent JButton: Objects appear in Background)

比較同一數組的元素 (Compare elements of the same array)

Java 屏幕截圖小程序 (Java screen capture applet)

Minecraft 1.8.9 Forge Modding 的Java 開發工具包,需要什麼JDK/JRE,代碼是否正確? (Java Development Kit with Minecraft 1.8.9 Forge Modding, What JDK/JRE Is Needed, Is Code Correct?)

java while (resultset.next()) 不返回同一列中的所有數據 (java while (resultset.next()) does not return all data in the same column)







留言討論