Java what is an array in division


ArrayList and Vector as generalized arrays

ArrayList and Vector are important representatives of the so-called collection classes. Container classes are extremely useful generalizations of the array concept. An array can hold a fixed number of objects of one type. The individual elements are accessed using an index. A container class can hold any number of objects of any type. In the case of ArrayList and Vector, the individual elements are also accessed using an index using a get () method.

Version 1.2 introduces the ArrayList class as part of the Collections hierarchy. The old class Vector was included in this hierarchy. As a result, the same (or similar) functionalities appear twice under different method names in the Vector class. In the Vector class there are both methods that deliver an enumeration and methods that deliver an iterator, since the iterator concept was only introduced in version 1.2. The ArrayList class largely replaces the Vector class. However, ArrayList is (intentionally) not thread safe. In applications where only one thread accesses the object, you can safely use the higher-performance ArrayList class.

In the API it says about Vector:

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized.

On the other hand, one reads about ArrayList:

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list.

For the ArrayList class you need the import java.util. *;

Important constructors
ArrayList ()
 
Constructs an empty ArrayList so that its internal data array has size 10 and its standard capacity increment is zero.
ArrayList (Collection c)
 
Constructs an ArrayList containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Important methods
Return typeName of the method
void
 
add (int index, Object element)
Inserts the specified element at the specified position in this ArrayList.
boolean
 
add (Object o)
Appends the specified element to the end of this ArrayList.
void
 
clear ()
Removes all of the elements from this ArrayList.
boolean
 
contains (Object element)
Tests if the specified object is a component in this ArrayList.
Object
 
get (int index)
Returns the element at the specified index.
int
 
 
indexOf (Object element)
Searches for the first occurrence of the given argument, testing for equality using the equals method.
Iterator
 
iterator ()
Returns an iterator over the elements in this list in proper sequence (inherited from AbstractList).
Object
 
lastElement ()
Returns the last component of the ArrayList.
Object
 
remove (int index)
Removes the element at the specified position in this ArrayList.
Object
 
set (int index, Object element)
Replaces the element at the specified position in this list with the specified element.
int
 
size ()
Returns the number of components in this ArrayList.
Object []
 
toArray ()
Returns an array containing all of the elements in this ArrayList in the correct order.

For the class Vector you need the import java.util. *;

Important constructors
Vector ()
 
Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
Vector (Collection c)
 
Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Important methods
Return typeName of the method
void
 
add (int index, Object element)
Inserts the specified element at the specified position in this vector.
boolean
 
add (Object o)
Appends the specified element to the end of this vector.
void
 
clear ()
Removes all of the elements from this vector.
boolean
 
contains (Object element)
Tests if the specified object is a component in this vector.
Object
 
elementAt (int index)
Returns the component at the specified index.
Enumeration
 
elements ()
Returns an enumeration of the components of this vector.
Object
 
get (int index)
Returns the element at the specified index.
int
 
 
indexOf (Object element)
Searches for the first occurrence of the given argument, testing for equality using the equals method.
Iterator
 
iterator ()
Returns an iterator over the elements in this list in proper sequence (inherited from AbstractList).
Object
 
lastElement ()
Returns the last component of the vector.
Object
 
remove (int index)
Removes the element at the specified position in this vector.
int
 
size ()
Returns the number of components in this vector.
Object []
 
toArray ()
Returns an array containing all of the elements in this vector in the correct order.

A vector is a dynamic array that grows in the background and can be used to include any objects. The following example takes some strings and some StringBuffers into a vector with add () and accesses them again with get (). In this process, however, objects of the Object type are returned and must be cast accordingly. In the following example you only want the elements from the Vector that are strings and check this with the instanceof operator.

import java.util. *; public class VectorDemo2 {public static void main (String [] args) {Vector v = new Vector (); v.add ("Anna"); v.add ("Luise"); v.add ("Christine"); v.add ("Agapi"); v.add (new StringBuffer ("Thomas")); v.add (new StringBuffer ("Walter")); v.add (new StringBuffer ("Julian")); v.add (new StringBuffer ("Max")); int len ​​= v.size (); for (int i = 0; i The elements () method supplies a list of the elements of the Vector as type enumeration. The interface enumeration is implemented as an anonymous class, as a look at the source code shows:

public enumeration elements () {return new enumeration () {int count = 0; public boolean hasMoreElements () {return count The successor to the Enumeration type is the Iterator interface. The iterator () method inherits Vector from AbstractList. In contrast to Enumeration, Iterator has an additional remove () method that can be used to remove an element from the list while iterating.


Type-safe ArrayList / Vector using generics

As already mentioned, an ArrayList or a Vector can hold any number of objects of any type. In a large number of applications, however, only objects of one and the same type are recorded (similar to an array). When accessing the recorded objects, however, objects with the basic type Objetct are always returned. So you will (have to) use a cast to work with the methods of the recorded objects. the following example should explain this.


The classic problem that led to the introduction of generics
ArrayList list = new ArrayList (); list.add ("Adam"); list.add ("Eva"); list.add ("Philemon"); list.add ("Baucis"); for (int i = 0; i Everything still works here. We cast the received objects to the string type (we know they are strings!) And this is the only way we can output the length of the individual strings in the loop. The class Object does not have a length () method.

ArrayList list = new ArrayList (); list.add ("Adam"); list.add ("Eva"); list.add ("Philemon"); list.add ("Baucis"); list.add (new StringBuilder ("Daphnis")); list.add (new StringBuilder ("Chloe")); for (int i = 0; i Somebody was not paying attention here and added two StringBuilder objects. A runtime error, a RuntimeException, occurs in the loop, whereas the compiler does not report an error. Basically, he has no way of determining a runtime error when compiling.

With the help of generics, however, the compiler is given the opportunity to discover such errors. This turns runtime errors into compiler errors. And the more errors you discover while completing, the fewer runtime errors there are.


Typed container classes

A newly introduced syntax (it is similar to that of templates in C ++) has been used since Java 1.5 to indicate that an ArrayList object, for example, is only to be generated for one type or for a group of types. When creating a container object, you specify which element type is to be saved. The new syntax enables a check at compile time and is therefore much less error-prone than the subsequent cast, which is now superfluous.


The above example now with the help of Generics
ArrayList list = new ArrayList (); // Type the array list object for strings list.add ("Adam"); list.add ("Eva"); list.add ("Philemon"); list.add ("Baucis"); for (int i = 0; i With the help of for each Loop this becomes even easier:

for (String name: list) // there are only strings in list! {System.out.println (name.length ()); }

And if we now want to include other objects as string objects, the compiler taps us on the finger:

ArrayList list = new ArrayList (); // Type the array list object for strings list.add ("Adam"); list.add ("Eva"); list.add ("Philemon"); list.add ("Baucis"); list.add (new StringBuilder ("Daphnis")); // Error at compiletime: cannot find symbol: method add (java.lang.Integer) list.add (new StringBuilder ("Chloe")); for (String name: list) {System.out.println (name.length ()); }

The compiler now knows that list can only accept string objects and adapts the signature of the methods accordingly. The add method, for example, no longer has the signature add (Object) but add (String). Hence the error message when we try to record a StringBuilder object.

Exercises on ArrayList / Vector