我正在尝试连接两个数组以向数字数组的列添加标签,并在数组的最后一行之后添加总数。我在另一个Stack Overflow线程How can I concatenate two arrays in Java?上找到了一些代码。但是我收到了错误
线程中的异常" AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object;不能转换为[[Ljava.lang.Object;
这是我的代码
public void getpdf(double[][] pricelist, ArrayList<Piece> in) {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage( page );
try {
PDPageContentStream contentStream =
new PDPageContentStream(doc, page);
JTable table=gettable(pricelist,in);
Object[] headercol={"Type","Asc","Ref","Commandes","Prix unitaire","Prix total"};
Object[][] content=getTableData(table);
Object[][] global=(Object[][]) concatenate (headercol,content);
//drawTable(page, contentStream, 700, 75, headercol);
drawTable(page, contentStream, 700, 75, content);
contentStream.close();
doc.save("bill.pdf" );
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public <T> T[] concatenate (T[] a, T[][] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen+bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
答案 0 :(得分:3)
public <T> T[] concatenate (T[] a, T[][] b)
您无法连接两个不同类型的数组。 a
是T
s的数组,b
是T[]
s的数组,即它是T
s的数组数组。
答案 1 :(得分:1)
您似乎想要连接T[] a
标头和T[][] b
内容,但您的concatenate
方法会返回T[]
。您必须返回T[][]
,即创建一个a.getClass()
而不是a.getClass().getComponentType()
的数组。此外,在新的T[][] c
中,T[] a
只占一个位置,因此总长度仅为b.length + 1
。试试这个:
public <T> T[][] concatenate (T[] a, T[][] b) {
T[][] c = (T[][]) Array.newInstance(a.getClass(), b.length + 1);
c[0] = a;
System.arraycopy(b, 0, c, 1, b.length);
return c;
}
由于以上只能将1D阵列连接到2D阵列,而不是相反(因为您需要在表格下方添加&#39;总计&#39;行,更一般方法是编写一个通用&#34;连接2个具有相同维度的数组&#34;方法,以及另一个将元素包装到数组中的方法。
public <T> T[] wrap(T x) {
T[] a = (T[]) Array.newInstance(x.getClass(), 1);
a[0] = x;
return a;
}
public <T> T[] concatenate (T[] a, T[] b) {
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), a.length + b.length);
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
示例:
String[] headercol = {"Type","Asc","Ref","Commandes","Prix unitaire","Prix total"};
String[][] content = {{"A","B","C","D","E","F","G","H"}, {"1","2","3","4","5","6","7","8"}};
String[] footer = {"a","b","c","d","e","f","g","h"};
String[][] global = (String[][]) concatenate (wrap(headercol),content);
global = (String[][]) concatenate (global, wrap(footer));
for (String[] row : global) {
System.out.println(Arrays.toString(row));
}
输出:
[Type, Asc, Ref, Commandes, Prix unitaire, Prix total]
[A, B, C, D, E, F, G, H]
[1, 2, 3, 4, 5, 6, 7, 8]
[a, b, c, d, e, f, g, h]