我可以使数组的每个索引等于 Java 中的不同字符串值吗?

Can I make each index of an array equal to a different String value in Java?

对于我正在制作的程序,我需要使 Files 数组的每个索引等于不同的 String 变量。我曾尝试使用 for 循环遍历每个索引,然后将其分配给不同的 String 变量,但没有成功。

代码:

final String user = System.getProperty("user.home");
final String OS = System.getProperty("os.name")
if (System.getProperty("os.name").equals("Mac OS X")){
        File folder = new File(user+"/example");
        // if file doesn't exist, then create it
        if (!folder.exists()){
            folder.mkdir();
        }

        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            System.out.println(listOfFiles[i].getName());
          } else if (listOfFiles[i].getName().equals(".DS_Store")){
              listOfFiles[i].delete();
          }
        }  
    }

如果你有一个 File[] 并且你想为数组的每个索引分配一个 String,你有两个选择,因为对象数组只能保存其指定的对象 class 和他们 class 的子 classes.

的对象

您的第一个选择是以 Object[] 而不是 File[] 开头。这样,假设你有 n 个文件

Object[] filesThenStrings = new Object[n];

//Populate filesThenStrings with File objects here, 
//this is legal since all classes are a subclass of Object 
//and java does upcasting for you

for(int i = 0; i < n; i++) {
  filesThenStrings[i] = someString; //where this is the string you
                                    //want to replace the i-th file with
}

不然的话,你也可以这样搞。再次假设 n 个文件,

File[] files = new File[n];

//populate here

String[] correspondStrings = new String[n];

for(int i = 0; i < n; i++) {
  correspondStrings[i] = someString; //where someString pertains to
                                     //files[i]
}