使用變量名作為數組索引 (Using variable name as array index)


問題描述

使用變量名作為數組索引 (Using variable name as array index)

I have few files which I put in array.  I shuffle the files so that it can be displayed in random order.  How to know that array index 0 is actually image1.txt or image2.txt or image3.txt? Thanks in advance.

String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);
Collections.shuffle(files); 

‑‑‑‑‑

參考解法

方法 1:

I'm not sure what you are trying to do.

To access the first element of the shuffled list, use files.get(0).

If you want to know where each element is gone, I suggest you take another approach to it. Create a list of integers from 0 to a.length() ‑ 1, inclusive and shuffle that list. Then manually permute the array a to a new collection.

方法 2:

INCORRECT ‑ see explanation

Note: Arrays.asList() will create a NEW list with the contents of the passed array. The original array will not be modified at all when you use Collections.shuffle().

Explanation

Peter has correctly pointed our that Arrays.asList() does NOT make a copy. The returned list is "write‑through" back to the original array. Shuffling the list will shuffle the contents of the original array. Also worth noting that the list is immutable (new elements cannot be added) but typically I find that the use of Arrays.asList() involves immutable lists anyway.

files.get(0); // get the first elements in shuffled list, random

// as greg said
int index = files.indexOf(a[0]); // find out where "image1.txt" is in the list
files.get(index); // get "image1.txt" back from the list

(by Jessymmxbasszero)

參考文件

  1. Using variable name as array index (CC BY‑SA 3.0/4.0)

#java #Variables #arrays






相關問題

電子郵件地址中帶有 + 字符的 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)







留言討論