Arrays
Most programming languages include the concept of an array to hold a collection of things, and the Java language is no exception. An array is nothing more than a collection of elements of the same type.You can declare an array in one of two ways:
- Create it with a certain size, which is fixed for the life of the array.
- Create it with a certain set of initial values. The size of this set determines the size of the array — it is exactly large enough to hold all of those values, and its size is fixed for the life of the array.
Declaring an array
In general, you declare an array like this:
1
| new elementType [arraySize] |
1
2
| // creates an empty array of 5 elements: int[] integers = new int[5]; |
1
2
| // creates an array of 5 elements with values: int[] integers = new int[] { 1, 2, 3, 4, 5 }; |
Another way to create an array is to create it and then code a loop to initialize it:
1
2
3
4
| int[] integers = new int[5]; for (int aa = 0; aa < integers.length; aa++) { integers[aa] = aa+1; } |
Loading an array
To load the array, you loop through the integers from 1 through the length of the array (which you get by calling.length
on the array — more
about that in a minute). In this case, you stop when you hit 5. Once the array is loaded, you can access it as before:
1
2
3
4
| Logger l = Logger.getLogger("Test"); for (int aa = 0; aa < integers.length; aa++) { l.info("This little integer's value is: " + integers[aa]); } |
1
2
3
4
| Logger l = Logger.getLogger("Test"); for (int i : integers) { l.info("This little integer's value is: " + i); } |
The element index
Think of an array as a series of buckets, and into each bucket goes an element of a certain type. Access to each bucket is gained using an index:
1
| element = arrayName [elementIndex]; |
The length
method
A handy method, as you've already seen, is length
. It's a built-in
method, so its syntax doesn't include the usual parentheses. Just type the word
length
, and it will return — as you would expect —
the size of the array. Arrays in the Java language are zero-based. So, for some array named
array
, the first element in the array always resides at
array[0]
, and the last resides at array[array.length -
1]
. An array of objects
You've seen how arrays can hold primitive types, but it's worth mentioning that they can also hold objects. In that sense, the array is the Java language's most utilitarian collection.Creating an array of
java.lang.Integer
objects isn't much different
from creating an array of primitive types. Once again, you have two ways to do it:
1
2
| // creates an empty array of 5 elements: Integer[] integers = new Integer[5]; |
1
2
3
4
5
6
| // creates an array of 5 elements with values: Integer[] integers = new Integer[] { Integer.valueOf(1), Integer.valueOf(2) Integer.valueOf(3) Integer.valueOf(4) Integer.valueOf(5)); |
Boxing and unboxing
Every primitive type in the Java language has a JDK counterpart class, which you can see in Table 4.Table 4. Primitives and JDK counterparts
Primitive | JDK counterpart |
---|---|
boolean | java.lang.Boolean |
byte | java.lang.Byte |
char | java.lang.Character |
short | java.lang.Short |
int | java.lang.Integer |
long | java.lang.Long |
float | java.lang.Float |
double | java.lang.Double |
Integer
:
1
2
| int value = 238; Integer boxedValue = Integer.valueOf(value); |
Similarly, to convert the
Integer
representation back to its
int
counterpart, you unbox it:
1
2
| Integer boxedValue = Integer.valueOf(238); int intValue = boxedValue.intValue(); |
Autoboxing and auto-unboxing
Strictly speaking, you don't need to box and unbox primitives explicitly. Instead, you can use the Java language's autoboxing and auto-unboxing features:
1
2
3
4
| int intValue = 238; Integer boxedValue = intValue; // intValue = boxedValue; |
Parsing and converting boxed types
You've seen how to obtain a boxed type, but what about parsing aString
that you suspect has a boxed type into its correct box? The JDK wrapper classes have
methods for that, too:
1
2
| String characterNumeric = "238"; Integer convertedValue = Integer.parseInt(characterNumeric); |
String
:
1
2
| Integer boxedValue = Integer.valueOf(238); String characterNumeric = boxedValue.toString(); |
String
expression (you've already seen this in calls to Logger
), the primitive
type is autoboxed, and wrapper types automatically have toString()
invoked on them. Pretty handy. Lists
AList
is a collection construct that is by definition an ordered
collection, also known as a sequence. Because a List
is
ordered, you have complete control over where in the List
items go. A
Java List
collection can only hold objects, and it defines a strict
contract about how it behaves. List
is an interface, so you can't instantiate it directly. You'll work
with its most commonly used implementation, ArrayList
. There are two
ways to make the declaration. First, using the explicit syntax:
1
| List< String > listOfStrings = new ArrayList< String >(); |
1
| List< String > listOfStrings = new ArrayList<>(); |
ArrayList
instantiation is not
specified. This is the case because the type of the class on the right side of the
expression must match that of the left side. Throughout the remainder of this
tutorial, I use both types, because you are likely to see both usages in practice. Note that I have assigned the
ArrayList
object to a variable of type
List
. With Java programming, you can assign a variable of one type
to another, provided the variable being assigned to is a superclass or interface
implemented by the variable being assigned from. You can look more at how variable
assignments are affected in Part 2 in the "Inheritance" section. Formal type
The<Object>
in the preceding code snippet is called the
formal type. <Object>
tells the compiler that this
List
contains a collection of type Object
, which means
you can pretty much put whatever you like in the List
. If you want to tighten up the constraints on what can or cannot go into the
List
, you can define the formal type differently:
1
| List< Person > listOfPersons = new ArrayList< Person >(); |
List
can only hold Person
instances.
Using List
s
Using List
s is super easy, like Java collections in general. Here are
some of the things you do with List
s: - Put something in the
List
. - Ask the
List
how big it currently is. - Get something out of the
List
.
List
by instantiating its ArrayList
implementation type, so you can start from there. To put something in a
List
, call the add()
method:
1
2
| List< Integer > listOfIntegers = new ArrayList<>(); listOfIntegers.add(Integer.valueOf(238)); |
add()
method adds the element to the end of the List
. To ask the
List
how big it is, call size()
:
1
2
3
4
5
| List< Integer > listOfIntegers = new ArrayList<>(); listOfIntegers.add(Integer.valueOf(238)); Logger l = Logger.getLogger("Test"); l.info("Current List size: " + listOfIntegers.size()); |
List
, call get()
and pass it
the index of the item you want:
1
2
3
4
| List< Integer > listOfIntegers = new ArrayList<>(); listOfIntegers.add(Integer.valueOf(238)); Logger l = Logger.getLogger("Test"); l.info("Item at index 0 is: " listOfIntegers.get(0)); |
List
would contain records, or business
objects, and you would possibly want to look over them all as part of your
processing. How do you do that in a generic fashion? You want to iterate over the
collection, which you can do because List
implements the
java.lang.Iterable
interface. (You learn about interfaces in Part 2.)
Iterable
If a collection implements java.lang.Iterable
, it's called an
iterable collection. You can start at one end and walk through the
collection item-by-item until you run out of items. You've already seen the special syntax for iterating over collections that implement the
Iterable
interface, in the "Loops" section.
Here it is again:
1
2
3
| for (objectType varName : collectionReference) { // Start using objectType (via varName) right away... } |
Iterating over a List
That previous example was abstract; now, here's a more realistic one:
1
2
3
4
5
| List< Integer > listOfIntegers = obtainSomehow(); Logger l = Logger.getLogger("Test"); for (Integer i : listOfIntegers) { l.info("Integer value is : " + i); } |
1
2
3
4
5
6
| List< Integer > listOfIntegers = obtainSomehow(); Logger l = Logger.getLogger("Test"); for (int aa = 0; aa < listOfIntegers.size(); aa++) { Integer I = listOfIntegers.get(aa); l.info("Integer value is : " + i); } |
index
variable
(aa
in this case) to initialize, and no call to the
List
's get()
method. Because
List
extends java.util.Collection
, which
implements Iterable
, you can use the shorthand syntax to iterate over
any List
. Sets
ASet
is a collections construct that by definition contains unique
elements — that is, no duplicates. Whereas a List
can contain
the same object hundreds of times, a Set
can only contain a given
instance once. A Java Set
collection can only hold objects, and it
defines a strict contract about how it behaves. Because
Set
is an interface, you can't instantiate it directly, so here
is one of my favorite implementations: HashSet
. HashSet
is
easy to use and is similar to List
. Here are some things you do with a
Set
: - Put something in the
Set
. - Ask the
Set
how big it currently is. - Get something out of the
Set
.
Using Set
s
A Set
's distinguishing attribute is that it guarantees uniqueness among
its elements but doesn't care about the order of the elements. Consider the
following code:
1
2
3
4
5
6
7
| Set< Integer > setOfIntegers = new HashSet< Integer >(); setOfIntegers.add(Integer.valueOf(10)); setOfIntegers.add(Integer.valueOf(11)); setOfIntegers.add(Integer.valueOf(10)); for (Integer i : setOfIntegers) { l.info("Integer value is: " + i); } |
Set
would have three elements in it, but it
only has two because the Integer
object that contains the value
10
is added only once. Keep this behavior in mind when iterating over a
Set
, like so:
1
2
3
4
5
6
7
8
9
10
| Set< Integer > setOfIntegers = new HashSet(); setOfIntegers.add(Integer.valueOf(10)); setOfIntegers.add(Integer.valueOf(20)); setOfIntegers.add(Integer.valueOf(30)); setOfIntegers.add(Integer.valueOf(40)); setOfIntegers.add(Integer.valueOf(50)); Logger l = Logger.getLogger("Test"); for (Integer i : setOfIntegers) { l.info("Integer value is : " + i); } |
Set
guarantees uniqueness, not order. You can see this if
you paste the previous code into the main()
method of your
Person
class and run it. Maps
AMap
is a handy collection construct that you can use to associate one
object (the key) with another (the value). As you might imagine,
the key to the Map
must be unique, and it's used to retrieve the value
at a later time. A Java Map
collection can only hold objects, and it
defines a strict contract about how it behaves. Because
Map
is an interface, you can't instantiate it directly, so here
is one of my favorite implementations: HashMap
. Here are some of the things you do with
Map
s: - Put something in the
Map
. - Get something out of the
Map
. - Get a
Set
of keys to theMap
— for iterating over it.
Using Map
s
To put something into a Map
, you need to have an object that represents
its key and an object that represents its value:
1
2
3
4
5
6
7
8
| public Map< String , Integer> createMapOfIntegers() { Map< String , Integer> mapOfIntegers = new HashMap<>(); mapOfIntegers.put("1", Integer.valueOf(1)); mapOfIntegers.put("2", Integer.valueOf(2)); mapOfIntegers.put("3", Integer.valueOf(3)); //... mapOfIntegers.put("168", Integer.valueOf(168)); } |
Map
contains Integer
s, keyed by a
String
, which happens to be their String
representation. To retrieve a particular Integer
value, you need its
String
representation:
1
2
| mapOfIntegers = createMapOfIntegers(); Integer oneHundred68 = mapOfIntegers.get("168"); |
Using Set
with
Map
On occasion, you might find yourself with a reference to a Map
, and you
want to walk over its entire set of contents. In this case, you need a
Set
of the keys to the Map
:
1
2
3
4
5
6
| Set< String > keys = mapOfIntegers.keySet(); Logger l = Logger.getLogger("Test"); for (String key : keys) { Integer value = mapOfIntegers.get(key); l.info("Value keyed by '" + key + "' is '" + value + "'"); } |
toString()
method of the Integer
retrieved
from the Map
is automatically called when used in the
Logger
call. Map
doesn't return a List
of
its keys because the Map
is keyed, and each key is unique. Uniqueness
is the distinguishing characteristic of a Set
.
0 comments:
Post a Comment