2010-06-18 68 views
2

我想知道如何將一種類型的列表轉換爲Java中使用推土機的另一種類型的數組。這兩種類型具有所有相同的屬性名稱/類型。例如,考慮這兩個類。將一種類型的列表轉換爲使用推土機的另一種類型的數組

public class A{ 
    private String test = null; 

    public String getTest(){ 
     return this.test 
    } 

    public void setTest(String test){ 
     this.test = test; 
    } 
} 

public class B{ 
    private String test = null; 

    public String getTest(){ 
     return this.test 
    } 

    public void setTest(String test){ 
     this.test = test; 
    } 
} 

我試過這個沒有運氣。

List<A> listOfA = getListofAObjects(); 
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); 
B[] bs = mapper.map(listOfA, B[].class); 

我也嘗試過使用CollectionUtils類。

CollectionUtils.convertListToArray(listOfA, B.class) 

這兩個都不適合我,誰能告訴我我做錯了什麼?如果我創建了兩個包裝類,其中一個包含List,另一個包含b [],mapper.map函數可以正常工作。請看下圖:

public class C{ 
    private List<A> items = null; 

    public List<A> getItems(){ 
     return this.items; 
    } 

    public void setItems(List<A> items){ 
     this.items = items; 
    } 
} 

public class D{ 
    private B[] items = null; 

    public B[] getItems(){ 
     return this.items; 
    } 

    public void setItems(B[] items){ 
     this.items = items; 
    } 
} 

這個工作很奇怪......

List<A> listOfA = getListofAObjects(); 
C c = new C(); 
c.setItems(listOfA); 
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); 
D d = mapper.map(c, D.class); 
B[] bs = d.getItems(); 

我怎麼做我想做的事情,而無需使用包裝類(C & d)?有一個更簡單的方法... 謝謝!

+1

在你最後上市的有一個錯字,映射命令應該是:d d = mapper.map(C ,D.class);試圖瞭解你的問題和例子。 – 2010-11-18 15:47:43

+0

謝謝,更正。 – aheuermann 2011-09-03 02:53:05

回答

3

在開始迭代之前,您知道listOfA中有多少項。爲什麼不實例化新的B [listOfA.size()],然後遍歷A,直接將新的B實例放入數組中。您將爲listOfB中的所有項目節省額外的迭代次數,並且代碼實際上更易於讀取以啓動。

Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); 

List<A> listOfA = getListofAObjects(); 
B[] arrayOfB = new B[listOfA.size()]; 

int i = 0; 
for (A a : listOfA) { 
    arrayOfB[i++] = mapper.map(a, B.class); 
} 
+0

你說得對,謝謝你的建議。 – aheuermann 2010-06-21 18:48:29

1

好吧,我是個白癡。我太習慣於推土機爲我做所有的工作......我所需要做的就是遍歷A列表並創建B列表,然後將列表轉換爲B列陣。

Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); 
List<A> listOfA = getListofAObjects(); 
Iterator<A> iter = listOfA.iterator(); 
List<B> listOfB = new ArrayList<B>(); 
while(iter.hasNext()){ 
    listOfB.add(mapper.map(iter.next(), B.class)); 
} 
B[] bs = listOfB.toArray(new B[listOfB.size()]); 

問題解決了!

0

它會更有意義,如果我可以寫下面的代碼和它的作品

List<A> listOfA = getListofAObjects(); 
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); 
B[] bs = mapper.map(listOfA, B[].class); 
+1

Namrata,我添加了一些空間到您的文章,以使其格式正確。您應該閱讀格式幫助。只需點擊下次發佈時文本框旁邊的「幫助」鏈接即可。 – 2011-05-06 12:55:50

相關問題