我有一个从字符串构建的多维数组,最初是用大小[50] [50]创建的,这个数组太大了,现在数组已满了空值,我目前正在尝试删除这些空值,我已经设法将数组的大小调整为[requiredSize] [50],但无法进一步缩小,任何人都可以帮助我吗?我已经在互联网上搜索了这样一个答案,但找不到它。Java:调整多维数组的大小
这里是我完整的代码太(我知道有可能是在我的代码一些非常不干净的部分,我还没有清理任何东西)
import java.io.*;
import java.util.*;
public class FooBar
{
public static String[][] loadCSV()
{
FileInputStream inStream;
InputStreamReader inFile;
BufferedReader br;
String line;
int lineNum, tokNum, ii, jj;
String [][] CSV, TempArray, TempArray2;
lineNum = tokNum = ii = jj = 0;
TempArray = new String[50][50];
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file path of the CSV");
String fileName = in.readLine();
inStream = new FileInputStream(fileName);
inFile = new InputStreamReader(inStream);
br = new BufferedReader(inFile);
StringTokenizer tok,tok2;
lineNum = 0;
line = br.readLine();
tokNum = 0;
tok = new StringTokenizer(line, ",");
while(tok.hasMoreTokens())
{
TempArray[tokNum][0] = tok.nextToken();
tokNum++;
}
tokNum = 0;
lineNum++;
while(line != null)
{
line = br.readLine();
if (line != null)
{
tokNum = 0;
tok2 = new StringTokenizer(line, ",");
while(tok2.hasMoreTokens())
{
TempArray[tokNum][lineNum] = tok2.nextToken();
tokNum++;
}
}
lineNum++;
}
}
catch(IOException e)
{
System.out.println("Error file may not be accessible, check the path and try again");
}
CSV = new String[tokNum][50];
for (ii=0; ii<tokNum-1 ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,TempArray[ii].length);
}
return CSV;
}
public static void main (String args[])
{
String [][] CSV;
CSV = loadCSV();
System.out.println(Arrays.deepToString(CSV));
}
}
的CSV文件看起来如下
Height,Weight,Age,TER,Salary
163.9,46.8,37,72.6,53010.68
191.3,91.4,32,92.2,66068.51
166.5,51.1,27,77.6,42724.34
156.3,55.7,21,81.1,50531.91
它可以显示任何大小,但这只是一个示例文件。
我只需要调整数组的大小,使它不会包含任何空值。
我也明白一个列表将是一个更好的选择,但这是不可能的,由于外部约束。它只能是一个多维数组。
如果使用列表是不是一种选择,你可以有你自己的动态数组实现,你的阵列扩大,因为和需要和新建的数组中复制旧的值时。或者你可以读两次文件。首先找到行数和列数,然后在第二次读取来定义数组,填入数组中的值 – 2010-10-18 18:24:43