Be Prepared ch 2.4-2.6 - Integer,Double, Arrays, ArrayLists, List Flashcards
ignore the weird § signs
Primitive data types
are not objects
In some situations it is convenient to represent numbers as objects
- Ex: you might want to store numeric values in an ArrayList, but the elements of an ArrayList must be objects.
- Java.lang package provides several wrapper classes that represent primitive data types as ojbects. Two of these classes, Integer and Double, are in the AP subest.
- Integer class has a constructor that takes an int value and creates an Integer object reprensenting that value. The IntValue() method of an Integer object returns the value represented by that object as an int.
• The Integer class also provides two symbolic constants that describe the range for int values:
§ Public static final int MIN_VALUE = -2147483648
§ Public static final int MAX_VALUE = 2147483647
Comparing
• Use .equals() method of the Integer or of the Double class if you want to compare two Integer or tow Double variables, respectively.
• == and != compare their address, not values
• The Integer and Double classes implement the Comparable and Comparable interfaces respectively so that each of these classes has a compareTo() method
§ Obj1.compareTo(obj2) returns a positive integer if obj1 is grater than obj2
§ 0 if same
§ Negative if less than
Autoboxing (Java 5.0+)
§ In certain situations, the compiler automatically converts values of primitive data types (int, double etc.) into the corresponding wrapper types (Integer, Double, etc.). This feature is called autoboxing (or autowrapping). For example, in
□ ArrayList numbers = new ArrayList();
□ Numbers.add(5)
□ //the second line is complied as
® Number.add(new Integer(5));
□ Likewires, where appropriate, the complier performs autounboxing.
® Int num = numbers.get(0);
® // is compiled as
◊ Int num = numbers.get(0).intValue();
• Two ways to declare and create a one-dimensional array
• SomeType[] a = new SomeType[size];
b = {value0, value1, value2 . . .};
2D Array
§ m.length = # rows
§ m[0].length = #columns, assuming a rectangular array
• A List holds objects of the specified type …
… • A List holds objects of the specified type E(for example, Strings or Integers) (Java 5.0+)
• The Java library provides two classes the implement List:
§ Java.util.ArrayList and java.util.LinkedList.
§ An arrayList stores the items in an array, and creates a new array and copies over the values whenever its array size changes; and a linked list uses a linked list structure.
How to create an ArrayList
• You can write ArrayList list = new ArrayList()
• Because ArrayList implements the List interface, you can also write:
§ List list = new ArrayList();
• You cannot instantiate an interface, so it is a mistake to write something like this:
§ List list = new List();
potato
a plant
nikhil
an animal