3

I have a variable (list) of type ArrayList[] and I want to save it in XML. I tried JAXB, but it saves only the "" String (the repetition of " is equal to list.length) and no items in ArrayLists. If I tried the 2d array it works fine. If I tried ArrayList, it works also fine. How can I solve this problem?

My code is similar to:

@XmlRootElement
public class SomeClass {

    @XmlElement(name="part")
    private final ArrayList<Object>[] list;

    ... constructor, which fills the list variable

}

Can someone tell me how to do this? Please.

Fortega
  • 19,463
  • 14
  • 75
  • 113
Matěj Polák
  • 182
  • 3
  • 10

3 Answers3

2

You should not mix generic types with arrays - Look at Item 25 in Effective Java. Use 2D array or list of lists.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • I used this type (ArrayList[]), because the length of the array is constant, so I thought it wasn't necessery to use the ArrayList>, but if is no other way I have to use this list of lists. Can I ask why I should not mix generic types with arrays? I don't see any problem (except JAXB saving) with this mixing... But thank you for your answer. – Matěj Polák Aug 16 '11 at 20:21
  • Thank you for explain me why I should not mix generic types and arrays. But if I used ArrayList> (list of lists) it is not still working. So I probably have to use XmlAdapter, but I dont now how to do this. – Matěj Polák Aug 17 '11 at 09:18
2

Thank yout for your effort, but I finally found a solution :). I covered one list by another class and it's working fine.:

@XmlElement(name="part)
MyClass[] list;

@XmlRootElement
class MyClass {
    @XmlElement(name="item")
    ArrayList<Object> list;    
}
Matěj Polák
  • 182
  • 3
  • 10
0

Do you really need an array of list objects? If not you could also use two lists:

Private LinkedList<LinkedList<Object>> parts;

This works well with jaxb.

rit
  • 2,308
  • 3
  • 19
  • 27
  • Ok, I will use it, I just thought is not necessery to use list of lists :), because the length of the array is final (constant). – Matěj Polák Aug 16 '11 at 20:24
  • I think if you initialize the array list instead of the linked list, there should be no difference. – rit Aug 16 '11 at 20:34
  • I think so too. But I think it is not necessery to use ArrayList> if I can use ArrayList[] (the length of the array is constant) – Matěj Polák Aug 16 '11 at 20:39
  • So, I tried ArrayList>, but it is still not working. Can someone help me how to make it work? I just need a list of lists and save it with JAXB to XML. – Matěj Polák Aug 16 '11 at 21:05