Collections
- Autoboxing
- Array List vs Linked List vs Queue
- Hash map vs Tree map
- untyped collections and wrapper class with untyped collections
- Wrapper classes for primitive types
- Byte (byte)
- Short (short)
- Integer (int)
- Long (long)
- Float (float)
- Double (double)
- Character (char)
- Boolean (boolean)
- Java Collection Framework (Collections is the basic methods):
- Lists (ordered) - ArrayList and LinkedList
- Sets (no dupicate) - HashSet
- Mapes (key value pair) - HashMap and TreeMap
- How it's different from Arrays
- Collections are classes in Java API, array is a Java Language feature.
- Collection classes have methods.
- Collections are varied in size.
- Collections are containers for objects, not for primitive types.
- Collections can process without indices while indices are usually required to process arrays.
- Generic collections
- ex. ArrayList<String> al = new ArrayList<String>();
Example
// This is an untyped array list ArrayList al = new ArrayList(); al.add("item1"); al.add("item2"); for (Object o : al) { ... } ArrayList p = new ArrayList(); p.add (new className (...)); for (int i = 0; i < p.size(); i++) { className c = (className)p.get(i); ... } // untyped array list will result in compiler warning // Note: file.java uses unchecked or unsafe operations. // Note: Recompile with -Xlint:unchecked for details. ArrayList Numbers = new ArrayList(); numbers.add(new Interger(1)); numbers.add("Mary"); // // and gives run time errors: // Exception in thread "main" java.lang.ClassCastException: java.lang.String // cannot be cast to java.lang.Integer at Demo.main(file.java:37) ArrayList numbers = new ArrayList(); numbers.add(new Integer(1)); numbers.add(new Integer(2)); numbers.add("Mary"); numbers.add("Helen"); for (int i = 0; i < numbers.size(); i++) { int number = (Integer)numbers.get(i); System.out.println(number); } // Use collection in a generic array ArrayList<String>codes = new ArrayList<String> (); codes.add("Mary"); codes.add("Helen"); codes.add("Raymond"); codes.add(100); //compiler error, wrong type, has to be String
System.out.println(codes); // Using wrappers for primitives ArrayList Numbers = new ArrayList(); numbers.add(new Integer(1));
Classes and Packages
- java.util.Arrays
- java.util.ArrayList
- Constructors
- ArrayList<E>()
- ArrayList<E>(intCapacity)
- ArrayList<E>(Collection)
- Methods:
- add(object)
- add(index, object)
- clear()
- contains(object)
- get(index)
- indexOf(object)
- isEmpty()
- remove(index)
- remove(object)
- set(index, object)
- size()
- toArray()
No comments:
Post a Comment