Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
swdev:java:lang:arraylist [2017/10/24 08:37]
smayr created
swdev:java:lang:arraylist [2017/10/25 08:49] (current)
smayr [ArrayList]
Line 1: Line 1:
-ArrayList =+List = 
 +List is a generic class that can handle most data.  
  
 +Initializing a ''List'':
 <code java> <code java>
-public ArrayList<Object> asArray()+import java.util.ArrayList
 +import java.util.List; 
 + 
 +// Method 1 
 +List<Object> arr = Arrays.asList( 
 +    1, "10001", "Acme Inc.", 1, null  
 +)
 + 
 +// Method 2 
 +List<Object> arr = new ArrayList<Object>(); 
 +arr.add(1); 
 +arr.add("10001"); 
 +arr.add("Acme Inc."); 
 +arr.add(1); 
 +arr.add(null); 
 +</code> 
 + 
 += ArrayList = 
 +''ArrayList'' is derived from ''List''. It can handle mixed primitives (as ''Object''). 
 +<code java> 
 +import java.time.LocalDateTime; 
 +import java.util.ArrayList; 
 +import java.util.List; 
 + 
 +public class MyRecord
 { {
 +  private Integer id;
 +  private String name;
 +  
 +  public ArrayList<Object> asArray()
 +  {
     ArrayList<Object> arr = new ArrayList<Object>();     ArrayList<Object> arr = new ArrayList<Object>();
                  
-    arr.add(id); +    arr.add(this.id); 
-    arr.add(name);+    arr.add(this.name);
                            
     return arr;     return arr;
 +  }
 +  
 +  public void fromArray(ArrayList<Object> arr)
 +  {
 +    this.id          = (Integer)arr.get(0);
 +    this.name        = (String)arr.get(1);
 +    this.created_at  = (LocalDateTime)arr.get(2);
 +    this.status      = (Boolean)arr.get(3);
 +  }
 +}
 +</code>
 +
 +To process each object with the correct type:
 +<code java>
 +ArrayList<Object> listOfObjects = new ArrayList<Object>();
 +for(Object obj: listOfObjects) {
 +   if (obj instanceof String) {
 +       // handle String
 +   } else if (obj instanceof Integer) {
 +       // handle Integer
 +   } else {
 +       // handle others
 +   }
 } }
-</code>    +</code>