Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
APCS Lecture Notes – Wrapper Classes -- Integer and Double Wrapper classes are used to make objects from primitive data types – int, double, boolean, etc. java.lang package provides “wrapper” classes for primitive data types to convert them to objects. Question: Why would we want to convert primitive data types to objects? Answer: To store them in our many Object–only data structures. Like String, wrapper classes are immutable -- they have NO modifier/mutator methods and, once created, can NEVER BE CHANGED internally. They can only be overwritten. Integer class constructor takes an int parameter Integer obj = new Integer(123); int num = obj.intValue(); //puts 123 in primitive int num Wrapper classes inherit several important methods from Object: 1. Use .equals() method when comparing two Integers or two Doubles 2. toString() shows the integer value in the object Important: == and != compare addresses, not values – Check for aliasing! Comparable interface class java.lang.Integer implements java.lang.Comparable Wrapper classes implement the Comparable interface compareTo method – obj1.compareTo(obj2) returns positive number if obj1 is greater than obj2 (like subtraction) returns negative number if obj1 is less than obj2 (like subtraction) returns 0 if obj1 is equal to obj2 (like subtraction) Introduction to Casting – The compiler complains ArrayList<Object> aL = new ArrayList<Object>(); aL.add(new Fraction(1,3)); System.out.println(aL.get(0)); //What if I just want to get the Fraction's numerator? System.out.println(aL.get(0).getNumerator()); //Fix: System.out.println(((Fraction)aL.get(0)).getNumerator()); The compiler must be able to find the definition of all methods before it will successfully compile. Sometimes you must direct it where to look. D:\582677150.doc