Documentation Archive Developer
Search
PATH Documentation > WebObjects

Table of Contents

NSArray


Inherits from:
Object
Implements:
Cloneable
java.io.Serializable
NSCoding
NSKeyValueCoding
NSKeyValueCodingAdditions
Package:
com.webobjects.foundation


Class Description


NSArray and its subclass NSMutableArray manage collections of objects called arrays. NSArray creates static arrays and NSMutableArray creates dynamic arrays.

Table 0-1 describes the NSArray methods that provide the basis for all NSArray's other methods; that is, all other methods are implemented in terms of these three. If you create a subclass of NSArray, you need only ensure that these base methods work properly. Having done so, you can be sure that all your subclass's inherited methods operate properly.


Table 0-1 NSArray's Base API
Method Description
count Returns the number of elements in the array.
objectAtIndex Provides access to the array elements by index.
objectsNoCopy Returns a natural language array containing the NSArray's objects.

The methods objectEnumerator and reverseObjectEnumerator grant sequential access to the elements of the array, differing only in the direction of travel through the elements. These methods are provided so that arrays can be traversed in a manner similar to that used for objects of other collection classes in both the Java API and the Foundation Kit, such as java.util.Hashtable or NSDictionary. See the objectEnumerator method description for a code excerpt that shows how to use these methods to access the elements of an array.

NSArray provides methods for querying the elements of the array. indexOfObject searches the array for the object that matches its argument. To determine whether the search is successful, each element of the array is sent an equals message. Another method, indexOfIdenticalObject, is provided for the less common case of determining whether a specific object is present in the array. indexOfIdenticalObject tests each element in the array to see its the exact same instance as the argument.

To act on the array as a whole, a variety of other methods are defined. You can extract a subset of the array ( subarrayWithRange) or concatenate the elements of an array of Strings into a single string ( componentsJoinedByString). In addition, you can compare two arrays using the isEqualToArray and firstObjectCommonWithArray methods. Finally, you can create new arrays that contain the objects in an existing array and one or more additional objects with arrayByAddingObject and arrayByAddingObjectsFromArray.


Operators

An NSArray works with NSArray.Operators to perform operations on the array's elements. By default, an array has operators defined for the following keys:


Key Operator Description
count Returns the number of elements in an array.
max Returns the element in the array with the highest value.
min Returns the element in the array with the lowest value.
avg Returns the average of the array's elements' values.
sum Returns the sum of the array's element's values.

To compute an operation on an array's elements, you use key-value coding methods with a specially formatted key. The character "@" introduces the name of the operator you want to perform. For example, to compute the average salary of an array's elements, you could use the method valueForKeyPath with "@avg.salary" as the key path. For more information, see the NSArray.Operator interface specification.

If you write your own operator class, you can make it available for use with NSArrays with the method setOperatorForKey. The operatorNames method returns the keys for the operators that NSArray knows about, and operatorForKey returns the operator for a specified key.




Constants


NSArray defines the following constants:


Constant Type Description
AverageOperatorName String A key representing the operator (an NSArray.Operator) that computes the average of the elements in an array.
CountOperatorName String A key representing the operator (an NSArray.Operator) that computes the number of elements in an array.
NotFound int Returned in the place of an index when an object is not found in an array. For example, indexOfObject returns NotFound if none of the receiver's objects are equal to the specified object.
MaximumOperatorName String A key representing the operator (an NSArray.Operator) that computes the largest element in an array.
MinimumOperatorName String A key representing the operator (an NSArray.Operator) that computes the smallest element in an array.
EmptyArray NSArray An empty array, which can be shared to save memory.
SumOperatorName String A key representing the operator (an NSArray.Operator) that computes the sum of the elements in an array.



Interfaces Implemented


Cloneable
clone
java.io.Serializable
NSCoding
decodeObject
classForCoder
encodeWithCoder
NSKeyValueCoding
takeValueForKey
valueForKey
NSKeyValueCodingAdditions
takeValueForKeyPath
valueForKeyPath


Method Types


Creating arrays
NSArray
immutableClone
mutableClone
arrayByAddingObject
arrayByAddingObjectsFromArray
sortedArrayUsingComparator
subarrayWithRange
Querying the array
containsObject
count
getObjects
indexOfObject
indexOfIdenticalObject
lastObject
objectAtIndex
objects
objectsNoCopy
objectEnumerator
reverseObjectEnumerator
vector
Comparing arrays
firstObjectCommonWithArray
isEqualToArray
Working with string elements
componentsJoinedByString
componentsSeparatedByString
Operations
operatorForKey
operatorNames
setOperatorForKey
removeOperatorForKey
Methods inherited from Object
equals
hashCode
toString
Sending messages to elements
makeObjectsPerformSelector


Constructors



NSArray

public NSArray()

Creates an empty, immutable array. After an immutable array has been initialized in this way, it can't be modified. If you need an empty, immutable array, use EmptyArray instead. This method is used by mutable subclasses of NSArray.

public NSArray(NSArray anArray)

Creates an array containing the objects in anArray. After an immutable array has been initialized in this way, it can't be modified.

public NSArray(Object anObject)

Creates an array containing the single element anObject. After an immutable array has been initialized in this way, it can't be modified. Throws an IllegalArgumentException if anObject is null.

public NSArray(Object[] objects)

Creates an array containing objects. Ignores any null values it encounters in objects. After an immutable array has been initialized in this way, it can't be modified.

public NSArray( Object[] objects, NSRange aRange)

Creates an array containing the objects from objects in the range specified by aRange. Ignores any null values it encounters in objects. After an immutable array has been initialized in this way, it can't be modified.

public NSArray( java.util.Vector aVector, NSRange aRange, boolean checkForNull)

Creates an array containing the objects from aVector in the range specified by aRange. After an immutable array has been initialized in this way, it can't be modified. The checkForNull argument controls the method's behavior when it encounters a null value in the vector: if checkForNull is true, the null value is simply ignored. If checkForNull is false, the method raises an IllegalArgumentException.


Static Methods



componentsSeparatedByString

public static NSArray componentsSeparatedByString( String string, String separator)

Returns an array containing substrings from string that have been divided by separator. The substrings in the array appear in the order they did in the receiver. If the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code excerpt:


String list = "wrenches, hammers, saws";
NSArray listItems = NSArray.componentsSeparatedByString (", ");

produces an array with these contents:


Index Substring
0 wrenches
1 hammers
2 saws

If list begins with a comma and space the array has these contents:


Index Substring
0 (empty string)
1 wrenches
2 hammers
3 saws

If list has no separators-for example, "wrenches"-the array contains the string itself, in this case "wrenches".

See Also: componentsJoinedByString



decodeObject

public static Object decodeObject(NSCoder coder)

Creates and returns an NSArray from the data in coder.

See Also: NSCoding Interface Description



operatorForKey

public static NSArray.Operator operatorForKey(String operatorName)

Returns the operator for the operator named operatorName.

See Also: "Operators" (page 4)



operatorNames

public static NSArray operatorNames()

Returns the names of the operations that can be performed on array elements. By default the operations are count, max, min, avg, and sum.

See Also: "Operators" (page 4)



removeOperatorForKey

public static void removeOperatorForKey(String operatorName)

Removes the operator identified by operatorName from the list of operators that can be performed on array elements.

See Also: "Operators" (page 4)



setOperatorForKey

public static void setOperatorForKey( String key, NSArray.Operator operator)

Sets the operator for key to operator. Throws an IllegalArgumentException if either key or operator are null.

See Also: "Operators" (page 4)




Instance Methods



arrayByAddingObject

public NSArray arrayByAddingObject(Object anObject)

Returns a new array that is a copy of the receiver with anObject added to the end. If anObject is null, an IllegalArgumentException is thrown.

See Also: addObject (NSMutableArray)



arrayByAddingObjectsFromArray

public NSArray arrayByAddingObjectsFromArray(NSArray otherArray)

Returns a new array that is a copy of the receiver with the objects contained in otherArray added to the end.

See Also: addObjectsFromArray (NSMutableArray)



classForCoder

public Class classForCoder()

Conformance to NSCoding. NSArray's implementation returns the class NSArray, so subclasses that don't override this method (such as NSMutableArray) are encoded as instances of NSArray.

See Also: classForCoder (NSCoding)



clone

public Object clone()

Simply returns the receiver. Since NSArrays are immutable, there's no need to make an actual clone.

componentsJoinedByString

public String componentsJoinedByString(String separator)

Constructs and returns a String that is the result of interposing separator between the elements of the receiver's array. For example, this code excerpt writes the path System/Developer to the console:

NSArray pathArray = new NSArray(new Object[] {'System', 'Developer'});
System.out.println('The path is '+ pathArray.componentsJoinedByString('/') + '.');

Each element in the receiver's array must handle either description, or if it is not implemented, toString. If the receiver has no elements, a String representing the empty string is returned.

See Also: componentsSeparatedByString



containsObject

public boolean containsObject(Object anObject)

Returns true if the receiver contains an object equal to anObject. This method determines whether an object is present in the array by sending an equals message to each of the array's objects (and passing anObject as the parameter to each equals message).

count

public int count()

Returns the number of objects currently in the array.

encodeWithCoder

public void encodeWithCoder(NSCoder coder)

Conformance to NSCoding. See the method description for encodeWithCoder in the NSCoding interface specification.

equals

public boolean equals(Object anObject)

Returns true if anObject is an NSArray and its contents are equal to the receiver's or false otherwise. If you know that anObject is an NSArray, use the more efficient method isEqualToArray instead.

firstObjectCommonWithArray

public Object firstObjectCommonWithArray(NSArray otherArray)

Returns the first object contained in the receiver that's equal to an object in otherArray, or null if no such object is found. This method uses equals to check for object equality.

getObjects

public void getObjects(Object[] buffer[])

Deprecated. Use public Object[] objects() instead.

public void getObjects( Object[] buffer[], NSRange aRange)

Deprecated. Use public Object[] objects(NSRange) instead.

hashCode

public int hashCode()

See the method description for hashCode in the Object class specification.

immutableClone

public NSArray immutableClone()

Returns an immutable copy of the receiver. Since an NSArray is immutable, NSArray's implementation simply returns the receiver. Subclasses such as NSMutableArray should override this method to create an immutable copy of the reciever.

indexOfIdenticalObject

public int indexOfIdenticalObject(Object anObject)

Searches all objects in the receiver for anObject (testing for equality by comparing object addresses) and returns the lowest index whose corresponding array value is identical to anObject. If none of the objects in the receiver are identical to anObject, this method returns NotFound.

public int indexOfIdenticalObject( Object anObject, NSRange aRange)

Searches the specified range within the receiver for anObject (testing for equality by comparing object addresses) and returns the lowest index whose corresponding array value is identical to anObject. If none of the objects in the range are identical to anObject, this method returns NotFound. Throws an IllegalArgumentException if aRange is out of bounds.

indexOfObject

public int indexOfObject(Object anObject)

Searches all objects in the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if equals returns true. If none of the specified objects are equal to anObject, returns NotFound.

public int indexOfObject( Object anObject, NSRange aRange)

Searches the specified range within the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if equals returns true. If none of the specified objects are equal to anObject, returns NotFound. Throws an IllegalArgumentException if aRange is out of bounds.

isEqualToArray

public boolean isEqualToArray(NSArray otherArray)

Compares the receiving array to otherArray, returning true if the contents of otherArray are equal to the contents of the receiver, false otherwise. Two arrays have equal contents if they each hold the same number of objects and objects at a given index in each array satisfy the equals test.

lastObject

public Object lastObject()

Returns the object in the array with the highest index value. If the array is empty, lastObject returns null.

makeObjectsPerformSelector

public void makeObjectsPerformSelector( NSSelector selector, Object[] anObject[])

Invokes the method specified by selector on each object in the receiver. The method is invoked each time with the values in anObject as the method's parameters. The method shouldn't, as a side effect, modify the receiver's collection of objects. The messages are sent using NSSelector's invoke method.

mutableClone

public NSMutableArray mutableClone()

Returns a mutable copy of the receiver. NSArray's implementation creates an NSMutableArray with the receiver's elements, not copies.

objectAtIndex

public Object objectAtIndex(int index)

Returns the object located at index. If the receiver is empty or if index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an IllegalArgumentException is thrown.

See Also: count



objectEnumerator

public java.util.Enumeration objectEnumerator()

Returns an enumeration that lets you access each object in the array, in order, starting with the element at index 0. For example, consider the following code excerpt:

java.util.Enumeration enumerator = myArray.objectEnumerator();

while (enumerator.hasMoreElements()) {
    Object anObject = enumerator.nextElement(); 
    /* code to act on each element */
}

When this method is used with mutable subclasses of NSArray, your code shouldn't modify the array during enumeration.

See Also: reverseObjectEnumerator



objects

public Object[] objects()

Returns copies of the receiver's elements in a natural language array.

public Object[] objects(NSRange aRange)

Returns copies of the receiver's elements that fall within the limits specified by aRange in a natural language array.

objectsNoCopy

protected Object[] objectsNoCopy()

Returns the receiver's actual elements-not copies-in a natural language array.

reverseObjectEnumerator

public java.util.Enumeration reverseObjectEnumerator()

Returns an enumeration that lets you access each object in the array, in order, from the element at the highest index down to the element at index 0. For example, consider the following code excerpt:


java.util.Enumeration enumerator = myArray.reverseObjectEnumerator();

while (enumerator.hasMoreElements()) {
    Object anObject = enumerator.nextElement(); 
    /* code to act on each element */
}

When this method is used with mutable subclasses of NSArray, your code shouldn't modify the array during enumeration.

See Also: objectEnumerator



sortedArrayUsingComparator

public NSArray sortedArrayUsingComparator(NSComparator comparator) throws NSComparator.ComparisonException

Returns an array that lists the receiver's elements, as determined by comparator. The new array contains the receiver's elements, not copies of them. Throws if the comparator's compare method throws for any reason.

sortedArrayUsingSelector

public NSArray sortedArrayUsingSelector(NSSelector selector) throws NSComparator.ComparisonException

Deprecated. Use sortedArrayUsingComparator instead.

subarrayWithRange

public NSArray subarrayWithRange(NSRange aRange)

Returns a new array containing the receiver's elements that fall within the limits specified by aRange. If aRange isn't within the receiver's range of elements, an IndexOutOfBoundsException is thrown.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).



NSRange theRange = new NSRange(0, wholeArray.count()/2);
NSArray halfArray = wholeArray.subarrayWithRange(theRange);



takeValueForKey

public void takeValueForKey( Object value, String key)

Conformance to NSKeyValueCoding. For each element in the receiver, NSArray's implementation sets the element's value for key to value. For example, if key is "firstName" and value is "Unknown", this method sets the firstName property of each of the receiver's elements to "Unknown".

takeValueForKeyPath

public void takeValueForKeyPath( Object value, String key)

Conformance to NSKeyValueCodingAdditions. For more information, see the takeValueForKeyPath method description in the NSKeyValueCodingAdditions interface specification.

toString

public String toString()

Returns a string representation of the receiver.

valueForKey

public Object valueForKey(String key)

Conformance to NSKeyValueCoding. NSArray's implementation is more complex than the default:

See Also: "Operators" (page 4)



valueForKeyPath

public Object valueForKeyPath(String keyPath)

Conformance to NSKeyValueCodingAdditions. NSArray's implementation is more complex than the default:

See Also: "Operators" (page 4)



vector

public java.util.Vector vector()

Returns the receiver as a Vector.

© 2001 Apple Computer, Inc. (Last Published April 17, 2001)


Table of Contents