Thinking in Java,fourth Edition (Java programming Idea, Fourth edition) Learning notes (11) Holding Your Objects

Source: Internet
Author: User
Tags addall iterable shuffle

To solve the programming problem, you need to create any number of objects, anytime, anywhere. So you can ' t rely on creating a named reference to hold each one of the your objects.

Java have several ways to hold objects:

1. The compiler-supported type is the array

Fixed-size

2. Container classes (or called collection classes, Java library uses the name collection to refer to a particular subset of the Library)

The Java.util Library has a reasonably complete set of container classes to solve this problem, the base types of which AR E List, Set,queue, and Map.

Generics and Type-safe containers

ArrayList

Arraylist<apple>

Basic Concepts

The Java container library divides into the distinct concepts, expressed as the basic interfaces:

1. Collection:a sequence of individual elements with one or more rules applied to them. A List must hold the elements in the the-the-they were inserted, a Set cannot have duplicate elements, and a Queue produc Es the elements in the order determined by a queuing discipline

2. Map:a Group of Key-value object pairs, allowing you-to-look-up a value using a key.

Although it's not always possible, ideally you'll write most of the your code-to-talk-to-these interfaces, and the only place Where you'll specify the precise type you ' re using are at the point of creation.

list<apple> apples = new arraylist<apple> ();

The intent of using the interface is so if you decide you want to change your implementation, all you need to do are Chan Ged it at the point of creation.

list<apple> apples = new linkedlist<apple> ();

But some concrete classes has additional functionality, if you need to use those methods, you won ' t is able to upcase to The more general interface.

Adding groups of elements

public class Addinggroups {

public static void Main (string[] args) {

collection<integer> Collection = new Arraylist<integer> (arrays.aslist ();

Integer[] moreints = {4,5,6};

Collection.addall (arrays.aslist (moreints));

Runs significantly faster, but can ' t

Construct a Collection this:

      Collections.addall (Collection, 11, 12, 13, 14, 15);

Collections.addall (collection, moreints);
Produces a list "backed by" an array:
list<integer> list = Arrays.aslist (16, 17, 18, 19, 20);
List.set (1, 99); OK--Modify an element
List.add (21); Runtime error because the underlying array (arrays$arraylist) cannot be resized.

However, Collections.addall () runs much faster, and it's just as easy-to-construct the Collection with no elements and the N Call Collections.addall (), so this is the preferred approach.

Collection.addall () member method can only take a argument of another Collection object, so it's not as flexible as Arra Ys.aslist () or Collections.addall ()

It ' s also possible to use the output of arrays.aslist () directly, as a List, but the underlying representation in this CA SE is the array, which cannot was resized. If you try to add () or delete () elements in such a list, which would attempt to change the size of an array, so you ll ge T an "unsupported operation" error at run time. 

A limitation of arrays.aslist () is that it takes a best guess about the resulting type of the List, and doesn ' t pay atten tion to what do you ' re assigning it to. Sometimes this can cause a problem:

Class Snow {}
Class Powder extends Snow {}
Class Light extends Powder {}
Class Heavy extends Powder {}
Class Crusty extends Snow {}
Class Slush extends Snow {}
public class Aslistinference {
public static void Main (string[] args) {
list<snow> Snow1 = Arrays.aslist (
New Crusty (), New Slush (), New Powder ());
    //Won ' t compile:
//List<snow> snow2 = Arrays.aslist (
//New Light (), new Heavy ());
//Compiler says:
//Found:java.util.list<powder>
//Required:java.util.list<snow>
Collections.addall () doesn ' t get confused:
list<snow> snow3 = new arraylist<snow> ();
Collections.addall (SNOW3, New Light (), new Heavy ());

Give a hint using an
Explicit type argument specification:
list<snow> snow4 = arrays.<snow>aslist(
New Light (), new Heavy ());
}
}

When trying to create Snow2, arrays.aslist () only have types of Powder, so it creates a list<power> rather than a Lis T<snow>, whereas Collections.addall () works fine because it knows from the first argument what's the target type is.

As can see from the creating of snow4, it's possible to insert a "hint" in the middle of Arrays.aslist (), to the compiler what the actual target type should is for the resulting List type produced by Arrays.aslist (). This was called an explicit type argument specification.

Printing containers

You must use Arrays.tostring () to produce a printable representation of an array,but the containers print nicely without a NY Help.

List

There is types of List:

1. The basic ArrayList, which excels a randomly accessing elements, but was slower when inserting and removing element in T He middle of a List.

2. The LinkedList, which provides optimal sequential access, with imexpensive insertions and deletions from the middle of The List. A LinkedList is relatively show for random access and it has a larger feature set than the ArrayList.

    

    

  

   List.sublist () produces a list backed by the original list. Therefore, changes in the returned list is reflected in the original list, and vice versa.

The Retainall () method is effectively a ' set intersection ' operation, in the ' case ' keeping all ' elements in copy that is also in Sub. Again, the resulting behavior depends on the Equals () method.

Convert any Collection to an array using ToArray (). This was an overloaded method; The no-argument version returns an array of Object, but if you pass a array of the target type to the overloaded version, It would produce an array of the type specified (assuming it passes type checking). If The argument array is too small to hold all the objects in the List (as are here), to Array () would create a NE W array of the appropriate size.

object[] o = Pets.toarray ();
pet[] pa = Pets.toarray (new pet[0]);

Iterator

It can be used on different type of containers without rewriting that code.

An iterator was an object whose job was to move through a sequence and select all object in that sequence without the Clien T programmer knowing or caring about the underlying structure of that sequence.

An iteratro are usually what's called a lightweight object:one that's cheap to create. For this reason, you'll often find seemingly strange constraints for iterators.

There ' s not much you can does with an Iterator except:

Iterator (): Get an iterator

Next (): Get the next object

Hasnext (): see if there is any further object in the sequence

Remove (): Remove the last element returned by the iterator

If you ' re simply moving forward through the list and not trying to modify the list object iteself, you can see that the fo Reach syntax is more succient

An Iterator would alos remove the last element produced by next (), which means your must call next () before-call remove ( ).

The power of the iterator:the ability to separate the operation of traversing a sequence from the underlying struct Ure of that sequence. For this reason, we sometimes say the iterators unify access to containers.

Listiterator

The Listiterator is a more powerful subtype of Iterator, which is produced only by List classes.

While Iterator can only move forward, Listiterator is bidirectional.

It can also produce the indexed of the next and previous elements relative to where the iterator are pointing in the list

It can replace the last element, the it visited using the set () method.

Listiterator (): produce a listiterator that points to the beginning of the List

Listiterator (n): Create a listiterator that starts out pointing to an index n in the list

Next (): Move back

Previous (): Move forward

Hasprevious ():

Hasnext ():

Previousindex (): Previous next () returns the index of the object

Nextindex (): Index of the next object in the sequence

LinkedList

efficiently insertion and removal in the middle of the list

Less efficient for random-access operations.

LinkedList also adds methods that allow it to be used as a stack a queue or a double-ended Queue (deque).

Some of these methods is aliases or slight variations of each and to produces names that is more familiar within the Context of a particular usage. For example:

GetFirst (), Element (): Return the head (first element) of the list Withou removing it, and throw nosuchelementexception if The List is empty.

Peek (): A slight variation of getfirst () and element () that returns null if the list is empty.

Removefirst (), remove (): Remove and return the head of the list, and throw nosuchelementexception for an empty list,

Poll (): a slight variation that return NULL if the this list is empty.

AddFirst (): Inserts an element at the beginning of the list

Offer (), add (), AddLast (): Add an element to the tail (end) of a list.

Removelast (): Removes and returns the last element of the list.

Stack

Last-in,first-out (LIFO)

A pushdown stack

LinkedList has methods this directly implement stack functionality, so can also just use a linkedlist rather than maki ng a stack class. However, a stack class can sometimes tell the story better.

Set

A Set refuses to hold more than one instance of each object value.

Hashset:optimized for Rapid Lookup

Set has the same interface as Collection. The Set is exactly a collection--it just have different behavior.

Hashset:uses hashing function for Speed

Treeset:keeps elements sorted into a red-black tree data structure.

Linkedhashset:use hashing for lookup speed, but appears to maintain elements in insertion order using a linked list.

Map

A MAP can return a set of its keys, a Collection of it values, or a set of its pairs.

Queue

First-in,first-out (FIFO)

Queues is commonly used as a by-reliably transfer objects from one area of a program to another.

Queues is especially important in concurrent programming.

LinkedList have methods to support queue behavior and it implements the queue interface, so a linkedlist can be used as a Q Ueue implementation.

Priorityqueue

FIFO describes the most typical queuing discipline. A queuing discipline is what decides, given a group of elements in the queue, which one goes next. FIFO says that the next element should is the one that is waiting the longest.

A priority queue says, that element, goes next is the one and the greatest need (the highest priority).

When you offer () an object onto a priorityqueue, that's object is sorted into the queue. The default sorting uses the natural order of the objects in the the queue, but can modify the order by providing your own Comparator. The Priorityqueue ensures if you call Peek (), poll () or remove (), the element you get would be the one with the high EST priority.

Collection vs. Interator

Collection:appeared because of commonality between other interfaces

Abstractcollection:provides a default implementation for a Collection, so the can create a new subtype of Abstractco Llection without unnecessary code duplication

In Java, implementing Collection also means providing an iterator method.

public static void display (iterator<pet> it) {

while (It.hasnext ()) {

Pet p = it.next ();

System.out.print (p.id () + ":" + P + "");

}

System.out.println ();

}

public static void display (Collection<pet> pets) {

for (Pet p:pets)

System.out.print (p.id () + ":" + P + "");

System.out.println ();

}

In this case the both approaches come up even. In fact, Collection pulls ahead a bit because it's iterable, and so in the implementation of display (Collection) the fore ACH construct can be used, which makes the code a little cleaner.

Producing an Iterator is the least-coupled A-connecting a sequence to a method that consumes that sequence, and puts Far fewer constraints on the sequence class than does implementing Collection.

Foreach and Iterators

Java SE5 introduced a new interface called Iterable which contains an iterator () method to produce an iterator, and the It Erable interface is what foreach uses to move through a sequence.

A foreach statement works with an array or anything iterable, and that's doesn ' t mean that's an array was automatically an Iter Able.

The Adapter Method idiom

Class Reversiblearraylist<t> extends Arraylist<t> {
Public reversiblearraylist (collection<t> c) {super (c);}
Publiciterable<t> reversed (){
return new iterable<t> () {
Public iterator<t> Iterator () {
return new iterator<t> () {
int current = size ()-1;
public Boolean Hasnext () {return current >-1;}
Public T Next () {return get (current--);}
public void Remove () {//Not implemented
throw new Unsupportedoperationexception ();
}
};
}
};
}
}
public class Adaptermethodidiom {
public static void Main (string[] args) {
reversiblearraylist<string> ral =
New Reversiblearraylist<string> (
Arrays.aslist ("To is or not to is". Split (")));
Grabs the ordinary iterator via iterator ():
for (String s:ral)
System.out.print (S + "");
System.out.println ();
Hand it the iterable of your choice

For (String s: ral.reversed ())
System.out.print (S + "");
}
}/* Output:
To is or not to IS
Be-to-not or is to

*/

  

public class Modifyingarraysaslist {
public static void Main (string[] args) {

Random rand = new Random (47);
Integer[] ia = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    
List<integer> list1 =
New Arraylist<integer> (Arrays.aslist (IA));
System.out.println ("Before shuffling:" + list1);
Collections.shuffle (List1, Rand);
System.out.println ("after shuffling:" + list1);
System.out.println ("array:" + arrays.tostring (IA));
List<integer> list2 = Arrays.aslist (IA);
System.out.println ("before shuffling:" + list2);
Collections.shuffle (List2, Rand);
System.out.println ("after shuffling:" + list2);
System.out.println ("array:" + arrays.tostring (IA));
}
}/* Output:
before shuffling: [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
after shuffling: [4, 6, 3, 1, 8, 7, 2, 5, 9]
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9,]
before shuffling: [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
after shuffling: [9, 1, 6, 3, 7, 2, 5, 10, 4, 8]
Array: [9, 1, 6, 3, 7, 2, 5, ten, 4, 8]
*/

Summary

Java provides a number of ways to hold objects:

1. Array:holds objects of a known type,can is multidimensional, can hold primitived. However, its size cannot is changed once you create it.

2. Collection:hold single elements, automatically resize, won ' t hold Primitives

3. Map:holds associated pairs, automatically resize, won ' t hold Primitives

4. Like an array, a List of also associated numerical indexes to Objects--thus,arrays and Lists is ordered containers.

5. The behavior of Queues and stacks is provided via the LinkedList

6. A Map is a-to-associate not integral values, but objects and other objects. Hashmaps was designed for rapid access, whereas a TreeMap keeps its keys in sorted order, and thus was not as fast as a have Hmap. A Linkedhashmap keeps its elements in insertion order, but provides rapid access with hashing.

7. A Set only accepts one of each type of object. Hashsets provide maximally fast lookups, whereas treesets keep the elements in sorted order. Linkedhashsets keep elements in insertion order.

8. There ' s no need to use the legacy classes Vector, Hashtable, and stacks in new code.

Thinking in Java,fourth Edition (Java programming Idea, Fourth edition) Learning notes (11) Holding Your Objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.