Rectangle 27 1

You could use JAXB with StAX to do the following:

import java.util.*;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(User.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        StreamSource xml = new StreamSource("src/forum17047306/input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);

        List<User> users = new ArrayList<User>();
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) {
            if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {
                User user = (User) unmarshaller.unmarshal(xsr);
                users.add(user);
            }
            xsr.next();
        }
        System.out.println(users.size());
    }

}

You may prefer the following approach for handling lists using a generic list wrapper object:

Unmarshall xml list of objects to java list without class list - Stack...

java xml jaxb annotations unmarshalling
Rectangle 27 6

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days. Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

Please show me a small example. I am passing Class<?> target and then getting target.getClassName().

Add a constructor as follows : JsonMarshallerUnmarshaller<T>{ private Class<T> targetClass ; JsonMarshallerUnmarshaller(Class<T> c){ targetClass = c ; } } Make appropriate changes now to the 'unmarshal' function to use this class instead of doing getClass everywhere.

Couple of notes: code can be simplified a lot by noting that all exceptions are subtypes of IOException (need just one catch), and that the default annotation introspector is already JacksonAnnotationIntrospector -- so no need to do anything to ObjectMapper, just construct it and it works.

java - Jackson and generic type reference - Stack Overflow

java json generics jackson
Rectangle 27 17

A first answer is to always return empty Lists, Sets, Arrays instead of null for method returning this kind of objects. Item 43 of Effective Java second edition from Joshua Bloch

Link is no longer active, just leads to the Java technetwork site

nullpointerexception - What's the best way to avoid lots of "if (obj !...

java nullpointerexception
Rectangle 27 17

A first answer is to always return empty Lists, Sets, Arrays instead of null for method returning this kind of objects. Item 43 of Effective Java second edition from Joshua Bloch

Link is no longer active, just leads to the Java technetwork site

nullpointerexception - What's the best way to avoid lots of "if (obj !...

java nullpointerexception
Rectangle 27 6

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

@Nitesh This is correct. StudentList is an object, not a List, as the error says

@Manos : - It is working now. Thanks a lot

How to convert JSON string into List of Java object? - Stack Overflow

java json jackson jackson-databind
Rectangle 27 6

Filtering the list based on the type

The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB, but of a different subclass of TestA, then the cast is not valid.

Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:

  • ... cast the whole list or
  • ... cast all elements of the list

The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.

The problem of debugging these spurious ClassCastExceptions can be alleviated with the Collections#checkedCollection family of methods.

A more type-safe way of converting from a List<Supertype> to a List<Subtype> is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null entries), but one possible implementation may look like this:

/**
 * Filter the given list, and create a new list that only contains
 * the elements that are (subtypes) of the class c
 * 
 * @param listA The input list
 * @param c The class to filter for
 * @return The filtered list
 */
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
    List<T> listB = new ArrayList<T>();
    for (Object a : listA)
    {
        if (c.isInstance(a))
        {
            listB.add(c.cast(a));
        }
    }
    return listB;
}

This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:

// A list of type "List<Number>" that actually 
// contains Integer, Double and Float values
List<Number> mixedNumbers = 
    new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));

// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);

System.out.println(integers); // Prints [12, 78]

java - How do you cast a List of supertypes to a List of subtypes? - S...

java list generics collections casting
Rectangle 27 9

Here are some efficient ways to warp Java object(s) in List, as of Java 8.

Collections.singletonList( object )

Collections.nCopies: One object, zero to many items, immutable, since 1.2. Collections.nCopies( number_of_copy, object ) High performance backed by internal class. All items point to same object.

Array.asList: Any number of objects, size immutable (individual elements mutable), since 1.2. Arrays.asList( object1, object2, object3 ) Backed by internal class. Items are converted to array at compile time and this array directly backs the List.

new ArrayList(Collection): Any number of objects, mutable, since 1.2new ArrayList<>( Arrays.asList( object1, object2, object3 ) ) The ArrayList is created with an array clone and an array copy, and so does not use any loops.

java - Utility method for wrapping an object in a collection - Stack O...

java collections
Rectangle 27 4

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

@Nitesh This is correct. StudentList is an object, not a List, as the error says

@Manos : - It is working now. Thanks a lot

How to convert JSON string into List of Java object? - Stack Overflow

java json jackson jackson-databind
Rectangle 27 4

It's hard to tell exactly what you are doing, but I think the problem is the constructor.

This makes a MatrixObject that shares the internals of copy, so any changes you make to either to the new or the old MatrixObject will actually change the other one. Instead you should copy all of the fields, like this:

public MatrixObject (MatrixObject copy) {

    this.startDate = new Date(copy.startDate.getTime());
    this.matrix = new int[copy.matrix.length][];
    for (int i = 0; i < copy.matrix.length; i++)
        this.matrix[i] = Arrays.copyOf(copy.matrix[i], copy.matrix[i].length);
}

Thanks! That worked like a charm. Appreciate all the comments. I am coming over from C# background and it great to get some help

Clone Object into array list, java - Stack Overflow

java object arraylist clone
Rectangle 27 35

Just because the reference to the list is immutable doesn't mean that the list it refers to is immutable.

Even if list was made final this would be allowed

// changing the object which list refers to
example.getList().add("stuff");

but this would not allowed:

// changing list
example.list = new ArrayList<String>();   // assuming list is public

In order to make the list immutable (prevent also the first line), I suggest you use Collections.unmodifiableList:

public class Example {
    final private ArrayList<String> list;

    Example(ArrayList<String> listArg) {
        list = Collections.unmodifiableList(listArg);
    }
}

(Note that this creates an unmodifiable view of the list. If someone is holding on to the original reference, then the list can still be modified through that.)

That is because a String is already immutable (unmodifiable) just as the list would be if you turned it into an unmodifiableList.

String data structure  | List data structure
           .-------------------------+------------------------------------.
Immutable  | String                  | Collection.unmodifiableList(...)   |
-----------+-------------------------+------------------------------------|
Mutable    | StringBuffer            | ArrayList                          |
           '-------------------------+------------------------------------'

AFAIK Collections.unmodifiableList() returns an immutable WRAPPER for given list. If I am correct, above will not guarantee immutability. A class may instantiate a list, instantiate Example, and can still modify the list that Example is holding by modifying the original list passed to the constructor. Albeit the answer may suffice to address the differences, it may fail to meet strict "immutability" requirements.

That's correct. Answer updated. You could do Collections.unmodifiableList(new ArrayList<>(listArg)) to make sure no one holds a reference to the underlying mutable list and thus avoid mutability.

java - Immutable Object with ArrayList member variable - why can this ...

java object immutability member getter-setter
Rectangle 27 16

The memory occupied by Java objects that are no longer accessible may be reclaimed by the virtual machine's garbage collector. As other have noted, this is automatic. In contrast, the normal operation of a program may allocate certain system resources that must be freed explicitly. Native screen resources are an example. A partial list of such methods inlcudes these:

What method in Java is used to destroy your objects - Stack Overflow

java
Rectangle 27 3

You need to implement equals and hashCode in the User class. If you don't have these methods implemented in User, listOld.contains(unique) will only return true if listOld contains exactly the same instance referenced by unique.

In Eclipse I auto generated equals and hashCode in the User class and my little loop still doesn't seem to detect that there are unique people in the new users versus the old users. Is auto generation a bad idea?

If you don't understand the code eclipse is generating, yes its a bad idea.

Java list of objects contained in another list of objects - Stack Over...

java list object contains
Rectangle 27 5

The two lists are referencing the same object. So if you change the first, the second will change also.

The solution is to clone the object (Creating a copy of it into a new instance) before adding it into the second list.

To clone the object you can either use one of the following suggestions:

1- A constructor by copy :

class HistoricRate {
  private String field;

  public HistoricRate (HistoricRate another) {
    this.field= another.field; // you can access  
  }
}

Implement the method clone to copy the object.

3- Use org.apache.commons.lang.SerializationUtils as below :

for (HistoricRate rate : rates){
    listOfRates.add(rate);
    inverseListOfRates.add(SerializationUtils.clone(rate));
}

java - I have two lists containing the same objects. How do I change o...

java list object deep-copy shallow-copy
Rectangle 27 6

Because an Integer is immutable. When you modify the value of the one referenced by a, you're creating a new object and updating the reference to it. testList holds a reference to both objects.

Adding the same object to List in Java - Stack Overflow

java
Rectangle 27 4

Picked
Book
Serializable
com.mif.vyub1222.biblioteka.Pasiemimas.

yeah, vyub1222.biblioteka.Pasiemimas is class Picked, I translated from my native language to english, but forgot to change errors :) @EJP

java - Serializing object that contains ArrayList of objects - Stack O...

java list object serialization arraylist
Rectangle 27 2

//To Array
    Pid[] pidArray = mapper.readValue(json, Pid[].class);

    //To List
    List<Pid> pidList1 = mapper.readValue(json, new TypeReference<List<Pid>>(){});

    //To List Another way
    List<Pid> pidList2 = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, Pid.class));

Converting a JSON with List in Java object - Stack Overflow

java json objectmapper
Rectangle 27 5

Since Integer wrapper class is immutable in java. Not only Integer, all wrapper classes and String is immutable.

a is a reference which points to an object. When you run a += 1, that reassigns a to reference a new Integer object, with a different value.

You never modified the original object.

What about class that I create ? Should change?

@Nominalista you can create MyClass, and sure, it can be mutable if you want, but you can't overload the += operator for it.

The new class is mutable if you have a method that updates its internal state.

Adding the same object to List in Java - Stack Overflow

java
Rectangle 27 11

That's right, but it's not the real story.

@mmyers In fact, that's what this question is all about. +1 for ChssPly76

java - Arrays.asList() not working as it should? - Stack Overflow

java arrays list variadic-functions