the set of java objects

Java Basics:

A collection of objects (top)
1. Arrays: Arrays and other containers difference is reflected in three aspects: efficiency, type of identification and can hold primitives. Java array is provided that can store and access reference random sequence of the many methods, the most efficient one. The array is a simple linear sequence, so it can quickly access just one element. But the speed comes at a price; When you create an array after its capacity on the fixed, but also in its life cycle can not be changed. generic java container classes including List, Set and Map. When they deal with objects as if these objects are not the same as their own specific type. In other words, the container will be all the elements it contains as a (Java root class of all classes) Object in. So you only need to create a container, you can put all types of objects are all put in here. Compared with other generic container, where an array of reflecting the second advantage: Creating an array, you also pointed out that it holds the object type (which in turn leads to my third point - the array can hold primitives , while the vessel was not). In other words, it will be at compile time type checking, thus preventing you insert the wrong type of object, or when the object is drawn into the type of object to the mistake.

2. Array is a first-class objects: Whether you're using the type of array, array identifiers are in fact a "created in the heap (heap) where the real object" reference. Is actually an object that holds other objects of reference. reference (Object) array with an array of different primitives is an array of objects to hold reference, while the primitive value of the array are directly held.
import com.bruceeckel.simpletest .*;
class Weeble () / / A small mythical creature
public class ArraySize (
public static void main (String [] args) (
/ / Arrays of objects:
Weeble [] a; / / Local uninitialized variable
Weeble [] b = new Weeble [5]; / / Null references
Weeble [] c = new Weeble [4]; / / an array of definitions for a
for (int i = 0; i <c.length; i + +)
if (c [i] == null) / / Can test for null reference
c [i] = new Weeble ();
/ / Aggregate initialization:
Weeble [] d = (new Weeble (), new Weeble (), new Weeble ()};// array of definitions for two
/ / Dynamic aggregate initialization:
a = new Weeble [] (new Weeble (), new Weeble ()};// array of definitions for three
System.out.println ( "a.length =" + a.length);
System.out.println ( "b.length =" + b.length);
/ / The references inside the array are
/ / Automatically initialized to null:
for (int i = 0; i <b.length; i + +)
System.out.println ( "b [" + i + "] =" + b [i ]);// even where there is no value of b can also be output, but is null only,
/ / The most important thing is Weeble [] b = new Weeble [5]; allocated space
System.out.println ( "c.length =" + c.length);
System.out.println ( "d.length =" + d.length);
a = d; / / change the point a,
System.out.println ( "a.length =" + a.length);
/ / Arrays of primitives:
int [] e; / / Null reference
int [] f = new int [5]; / / an array of definitions for a
int [] g = new int [4];
for (int i = 0; i <g.length; i + +)
g [i] = i * i;
int [] h = (11, 47, 93); / / array of definitions for two
/ / Compile error: variable e not initialized:
/ /! System.out.println ( "e.length =" + e.length);
System.out.println ( "f.length =" + f.length);
/ / The primitives inside the array are
/ / Automatically initialized to zero:
for (int i = 0; i <f.length; i + +)
System.out.println ( "f [" + i + "] =" + f [i]);
System.out.println ( "g.length =" + g.length);
System.out.println ( "h.length =" + h.length);
e = h; / / change the point e
System.out.println ( "e.length =" + e.length);
e = new int [] (1, 2); / / array of definitions for three
System.out.println ( "e.length =" + e.length);
) ///:~

3. Returns an array: if you write a method, which returns not one but a group of things. In the C and C + +-like languages, this matter a bit difficult it has. Because you can not return an array, you can only return a pointer to an array. The treatment of "control an array of life-cycle" sort of trouble, doing so could easily be wrong, leading to a memory leak. Java takes a similar solution, but the difference is that it returns "is an array." With the C + + different, you'll never do not have to worry about Java, the array - as long as you need it, it is still; Once you run out, the garbage collector will help you clean it up. (Ie You can put different types of things that are stuffed at the same time, conducted an array of return, as long as you know what that is on the line. This situation can also be suitable for Java and other containers)
import com.bruceeckel.simpletest .*;
import java.util .*;
public class IceCream (
private static Random rand = new Random ();
public static final String [] flavors = (
"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
"Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie"
public static String [] flavorSet (int n) (
String [] results = new String [n];
boolean [] picked = new boolean [flavors.length];
for (int i = 0; i <n; i + +) (
int t;
t = rand.nextInt (flavors.length);
while (picked [t]);
results [i] = flavors [t];
picked [t] = true;
return results;
public static void main (String [] args) (
for (int i = 0; i <20; i + +) (
System.out.println (
"flavorSet (" + i + ") =");
String [] fl = flavorSet (flavors.length);
for (int j = 0; j <fl.length; j + +)
System.out.println ( "\ t" + fl [j]);
) ///:~

4.Arrays Class: java.util inside a Arrays class, which includes a set can be used for an array of static methods that are some utility. There are four basic methods: to compare two arrays equal if equals (); is used to populate the array fill (); is used to sort the array sort (); and used in a sorted array Find element binarySearch (). All of these methods are carried out on the primitive and Object overloading. There is also a asList () method, which accepts an array, and then turn it into a List container.
(1) fill () method, but it was too simple; it simply copies the value into an array of different location, if it is an object, it will reference the same copy to each location, such as:
int [] a5 = new int [10];
Arrays.fill (a5, 19); / / a5 each location of the array is 19
String [] a9 = new String [10];
Arrays.fill (a9, "Hello ");// a9 each location of the array is" Hello "
Arrays.fill (a9, 3, 5, "World ");// with the" World "to fill a [3], a [4], packets are incomplete packet.
(2) java standard library provides a System.arraycopy () to static methods. Than for loop, it can copy an array at a faster pace. Such as:
int [] i = new int [7];
int [] j = new int [10];
Arrays.fill (i, 47);
Arrays.fill (j, 99);
System.arraycopy (i, 1, j, 0, i.length-1); / / put i into j test, the one for i, subscript, 0 for the beginning of j subscript, i.length-1 for j the end of the subscript (3) Arrays provided by the overloaded equals () method. Of course, but also for a variety of primitive and Object of. To complete two arrays are equal, they must have the same number of elements, but each element of the array to another array must correspond to the position of the elements are equal. Elements of equality, using eqauls () to judge. (For primitive, it will use its wrapper class equals (); such as int using Integer.equals ().) For example:
import com.bruceeckel.simpletest .*;
import java.util .*;
public class ComparingArrays (
public static void main (String [] args) (
int [] a1 = new int [10];
int [] a2 = new int [10];
Arrays.fill (a1, 47);
Arrays.fill (a2, 47);
System.out.println (Arrays.equals (a1, a2));
a2 [3] = 11;
System.out.println (Arrays.equals (a1, a2));
String [] s1 = new String [5];
Arrays.fill (s1, "Hi");
String [] s2 = ( "Hi", "Hi", "Hi", "Hi", "Hi");
System.out.println (Arrays.equals (s1, s2 ));// array is equal is based on its content, (through Object.equals ()),)
) ///:~

(4) Arrays.sort (a) can be an array of a (a can be any of an array) to be sorted. Built-in sort method is an array of any sort, whether primitive or an array of objects, as long as it implements the Comparable interface or there is a related Comparator (for an array of objects, primitive arrays are not allowed to use Comparator) interface on the list. [1]: Comparable interface, to override a method compareTo (), this method can accept another object as a parameter, if the existing object smaller than the argument, it will return a negative number, if the same is returned to zero, if the existing objects than the parameters of large, it returns a positive number. [2] Comparator interface, there are two methods compare () and equals (). But unless there is a special performance requirements, or you do not need to go to achieve the equals (). As long as a class, it is implicitly inherited from Object, the Object which already has an equals () has. So you do can use the default Object's equals (), so had to meet the interface requirements of the. Arrays.asList () method to transform an array into a List: If
List a = Arrays.asList ( "one two three four five six seven eight". Split ( ""));

Examples [1]:
import com.bruceeckel.util .*;
import java.util .*;
public class CompType implements Comparable (
int i;
int j;
public CompType (int n1, int n2) (
i = n1;
j = n2;
public String toString () (
return "[i =" + i + ", j =" + j + "]";
public int compareTo (Object rv) (
int rvi = ((CompType) rv). i;
return (i <rvi? -1: (i == rvi? 0: 1));
private static Random r = new Random ();
public static Generator generator () (
return new Generator () (
public Object next () (
return new CompType (r.nextInt (100), r.nextInt (100));
public static void main (String [] args) (
CompType [] a = new CompType [10];
Arrays2.fill (a, generator ());
System.out.println (
"before sorting, a =" + Arrays.asList (a));
Arrays.sort (a);
System.out.println ( "after sorting, a =" + Arrays.asList (a));
) ///:~
If CompType does not implement Comparable interface, then the program is running calls to sort () when it gives rise to a ClassCastException error. This is because the sort () will convert its argument passed to Comparable.

Example [2]:
import com.bruceeckel.util .*;
import java.util .*;
class CompTypeComparator implements Comparator (
public int compare (Object o1, Object o2) (
int j1 = ((CompType) o1). j;
int j2 = ((CompType) o2). j;
return (j1 <j2? -1: (j1 == j2? 0: 1));
public class ComparatorTest (
public static void main (String [] args) (
CompType [] a = new CompType [10];
Arrays2.fill (a, CompType.generator ());
System.out.println ( "before sorting, a =" + Arrays.asList (a));
Arrays.sort (a, new CompTypeComparator ());// the use of Comparator comparison to arrange a array,
/ / Compare method of the automatic call
System.out.println ( "after sorting, a =" + Arrays.asList (a));
) ///:~

(5) Inquiry ordered array, the array row, once finished sequence, you can use Arrays.binarySearch () for quick queries. However, we must guard against a yet to sort an array using the binarySearch (); because the results do not make sense. If Arrays.binarySearch () is found, it returns a greater than or equal to 0
Value. Otherwise, it returns a negative value, and this negative trying to say is that if you manually maintaining this array, then this value should be inserted at which position. This value is: (insertion point) -1, "insertion point" that is, in all "than looking for that value," greater value, the smallest value of the subscript of that, or, if all values in the array than to find the value of the small, it is a.size (). If there are duplicate elements inside the array, then it can not guarantee which one will return. If the sort used when the Comparator, then binarySearch () time, it must use the same Comparator (using this method overloaded version).
import com.bruceeckel.simpletest .*;
import com.bruceeckel.util .*;
import java.util .*;
public class AlphabeticSearch (
public static void main (String [] args) (
String [] sa = new String [30];
Arrays2.fill (sa, new Arrays2.RandStringGenerator (5));
CompTypeComparator comp = new CompTypeComparator ();
Arrays.sort (sa, comp); / / use Comparator to sort comparison
int index = Arrays.binarySearch (sa, sa [10], comp); / / must also use Comparator to compare
System.out.println ( "Index =" + index);
) ///:~

(6) container Description: Java's container classes divided into two basic types. The difference between them in each location to put the number of objects. Collection only allows an object placed on each location (the name is a bit misleading, because the container class libraries are often referred to as collections). It includes "a certain order to hold a group of objects," the List, as well as the "only allows the addition of non-repetition of the object" Set. ArrayList is a List, and HashSet is a Set. You can use the add () method to Collection objects inside Canada. Map to save the "key (key) - the value of" form of the pair, rather like a mini-database. Above, this program uses a HashMap called the Map. If you have built a "state and capital" of the Map, and then want to check where the capital of Ohio, you can use it to come to the. Usage and search an array with the subscript is the same. (Map is also known as the relevance of an array of associative array.) You can use the put () method to add elements inside the Map. It accepts key - value pair as a parameter form.
List will be honest to hold all the objects you have entered is neither an editor nor do sorting. Set accept only one of each object, but also with its own rules to re-sort the elements (under normal circumstances, you are only concerned with Set package did not include an object, rather than where it is ranked in the end - if it is so, do you best to use List). Map does not receive duplicate pair, whether it is not repeat, it requires the key to decide. In addition, it also has its own internal sorting rules, will not be affected by the input sequence. If the insertion order is very important, then you can only use LinkedHashSet or LinkedHashMap has.
Collection and Map by default, print the output (using the container class toString () method), their effect is good, so we will no longer provide additional printing support. The Collection will be printed in square brackets, elements and between elements separated by commas. Map will use to spend, in brackets, between the keys and values associated with the equal sign up (key on the left, the value of the right).

(7). Container Disadvantages: do not know the type of object: Java container has a drawback, that is, to put the object inside the container when the type of information to the object will lose it. This is because the development of the container class, the programmer will not know you want to use it to save what type of object, and let the container merely to save a particular type of object would affect its versatility. Therefore, containers are made only to holders of Object, which is the root of all objects in the class reference, so that it can hold any type of object. (Of course, does not include primitive, because they are not objects, there is no other objects inherit.) This is a very great program, but:
[1] due to the object into the container, it's the type of information is discarded, so the container on the "can drive what type of objects added," There is no limit. For example, even if you only want to hold cat, people can easily put the dog to go.
[2] Because the object type information was lost, the container only know that it holds the Object of reference, so the object prior to use (in the container when removed) also must be type conversion.

(8) iterator: "iterator (iterator)" concept (also a design pattern) is used to achieve this abstract. Iterator is an object, its task is to be able to let "the client programmer not know, or do not care about his dealing with what the underlying sequence structure" case, will be able to move around an object in the sequence , and select one of these objects. java of the iterator can do things:
[1] using iterator () method is called the container to pass you a Iterator object. The first call to Iterator's next () method, it will pass you the first element in the sequence.
[2] with the next () method to get the next sequence of an object.
[3] to use hasNext () method queries whether there are other objects in the sequence.
[4] using remove () method to delete iterators returned by the last element.
package c11;
public class Cat (
private int catNumber;
public Cat (int i) (catNumber = i;)
public void id () (
System.out.println ( "Cat #" + catNumber);
public String toString () (
System.out.println ( "Cat''id =" + catNumber);
) ///:~

package c11;
import com.bruceeckel.simpletest .*;
import java.util .*;
public class CatsAndDogs2 (
public static void main (String [] args) (
List cats = new ArrayList (); / / ArrayList is an array of automatically extended, but he is a List
for (int i = 0; i <7; i + +)
cats.add (new Cat (i));
Iterator e = cats.iterator (); / / Iterator are created
while (e.hasNext ()) / / first use hasNext () to determine
((Cat) ()). Id ();
System.out.println ( ());// direct calls toString () method.
) ///:~

(9) Collection features: Collection of all the features, that is, you can use Set and List do anything (not including auto-inherited from the Object method).
[1] boolean add (Object): to ensure that the container can hold parameters that you pass it. If you failed to get it incorporated, it returns false. (This is an "optional" approach, this chapter will further explain later.)
[2] boolean addAll (Collection): Add parameter Collection contains all the elements. As long as the added element, it returns true. ( "Optional")
[3] void clear (): remove the container kept by all the elements. ( "Optional")
[4] boolean contains (Object): If a container holding parameter Object, returns true.
[5] boolean containsAll (Collection): If a container holding all the elements contained in the parameter Collection, it returns true.
[6] boolean isEmpty (): If a container which did not save any element, it returns true.
[7] Iterator iterator (): Returns a container can be moved between the various elements of the Iterator.
[8] boolean remove (Object): If a container inside the parameter Object, then put one of them to delete the phrase. Simply delete the stuff off, it returns true. ( "Optional")
[9] boolean removeAll (Collection): Remove all of the parameters inside the container Collection contains elements. As long as things had deleted, it returns true. ( "Optional").
[10] boolean retainAll (Collection): Only save the parameters included in the Collection of the elements (set theory, the "intersection" of the concept). If changes occurred, then returns true. ( "Optional")
[11] int size (): Returns the number of elements contained in the container.
[12] Object [] toArray (): Returns a container that contains all the elements of the array.
[13] Object [] toArray (Object [] a): returns a container that contains all the elements of the array, and that this array is not an ordinary Object array, its type should be an array of a type with the parameters of the same (to do type conversion) .

(10) List of features: ist The basic usage is to use add () add an object, use get () take an object, using iterator () to obtain the sequence of the Iterator.
[1] List (Interface): List of the most important feature is the orderly; it will ensure that certain elements in order to save. List on the basis of the Collection to add a lot of ways to enable the middle of insertion and deletion in the sequence elements. (Only for LinkedList recommended.) List can be created ListIterator object, you can use it apart from the middle of the List elements in addition to insertion and deletion, but also use it in both directions along the traverse List.
[2] ArrayList *: an implementation using an array of List. Available for quick random access, but the list to insert and delete elements in the middle of the time is slower. ListIterator only be used in the reverse traversal ArrayList occasions, do not use it to insert and remove elements, as compared to LinkedList, in the ArrayList using ListIterator system inside the relatively high overhead.
[3] LinkedList: optimized for sequential access. In the middle of insert and delete elements List price is not high. The relatively slow random access. (Using ArrayList bar.) In addition, it also has addFirst (), addLast (), getFirst (), getLast (), removeFirst () and removeLast () and other methods (these methods, interfaces and base classes were not defined), you can Think of it as the stack (stack), Queue (queue), or double-ended queue (deque) use.

(11) Set features: Set is the Collection interface, so unlike the two List, it has no extra features. Set will refuse to hold multiple values with the same instance of the object (the object's "value" is again what determines it? This problem is rather complicated, we will talk about later).
[1] Set (Interface): Add Set each element must be unique; otherwise, Set is not it added to the. To add into the Set, Object must define equals (), so as to indicate the object is unique. Set exactly the same interface and Collection. Set the interface does not guarantee that it will use to store the elements in which sequence.
[2] HashSet *: In order to optimize query speed and the design of Set. To put the definition of HashSet inside the Object have to hashCode ().
[3] TreeSet: is an orderly Set, whose bottom is a tree. Set inside so that you will be able to extract from an ordered sequence of the.
[4] LinkedHashSet (JDK 1.4): an in-house using the list of Set, both HashSet query speed, but also save the element is added to the order to (insert order). Set to use Iterator traversal when it is based on insertion order visit.
HashSet the order is to save the object and the TreeSet and LinkedHashSet not the same. This is because they are different ways to store and search for elements. (TreeSet with a red-black tree data structure called 『red-black treedata structure to come to sort the element, while the HashSet is used the word" specifically designed for rapid search, "the hash function. LinkedHashSet in-house use hashing to to improve query speed, but it looks like a linked list to hold the elements with the insertion order.) you write your own class time, we must remember, Set to have a judge in what order to store the elements in the standard, that is You must implement the Comparable interface, and the definition of compareTo () method. Here is an example:
/ /: C11:
/ / Putting your own type in a Set.
import com.bruceeckel.simpletest .*;
import java.util .*;
public class Set2 (
public static Set fill (Set a, int size) (
for (int i = 0; i <size; i + +)
a.add (new MyType (i));
return a;
public static void test (Set a) (
fill (a, 10);
fill (a, 10); / / Try to add duplicates
fill (a, 10);
a.addAll (fill (new TreeSet (), 10));
System.out.println (a);
public static void main (String [] args) (
test (new HashSet ());
test (new TreeSet ());
test (new LinkedHashSet ());
) ///:~
Whether it is kind of Set, you should define equals (), but only in the "take an object into a HashSet" the case, you only need to define hashCode () (better definition of a, as usually HashSet yes Set the preferred). But as a programming style, you should override equals () at the same time the hashCode () has also overwrite the.
SortedSet: SortedSet (this is only an implementation of TreeSet available) elements must be orderly. This makes the SortedSet interface, a few more methods (note that, SortedSet meaning "according to the order of the object of comparison" rather than "Insertion Order" to sort.):
[1] Comparator comparator (): Returns the Comparator used for Set object, or with null, said it uses the Object own sorting method.
[2] Object first (): Returns the smallest element.
[3] Object last (): Returns the largest element.
[4] SortedSet subSet (fromElement, toElement): Returns a subset of Set in which the elements from start to toElement until fromElement (including fromElement, does not include toElement).
[5] SortedSet headSet (toElement): Returns a subset of Set, in which the element should be less than toElement.
[6] SortedSet headSet (toElement): Returns a subset of Set, in which the element should be greater than fromElement.

Article Source:

分类:Java 时间:2010-03-29 人气:319
blog comments powered by Disqus


iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 黔ICP备15002463号-1

processed in 0.775 (s). 12 q(s)