問題描述
將兩個單獨的 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 Redandwhite、Nick Rippe、msell)