📄 tij312.htm
字号:
<font color=#0000ff>public</font> String toString() { <font color=#0000ff>return</font> Integer.toString(i); }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>Next, we need a tool that holds two things together: an indicator of the <b>Pet</b> type and a <b>Counter</b> to hold the pet quantity. That is, we want to be able to say “how may <b>Gerbil</b> objects are there?” An ordinary array won’t work here, because you refer to objects in an array by their index numbers. What we want to do here is refer to the objects in the array by their <b>Pet</b> type. We want to <i>associate</i> <b>Counter</b> objects with <b>Pet</b> objects. There is a standard data structure , called an <i>associative array</i>, for doing exactly this kind of thing. Here is an extremely simple version: <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0483" title="Send BackTalk Comment">Feedback</a></font><br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c10:AssociativeArray.java</font>
<font color=#009900>// Associates keys with values.</font>
<font color=#0000ff>package</font> c10;
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;
<font color=#0000ff>public</font> <font color=#0000ff>class</font> AssociativeArray {
<font color=#0000ff>private</font> <font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
<font color=#0000ff>private</font> Object[][] pairs;
<font color=#0000ff>private</font> <font color=#0000ff>int</font> index;
<font color=#0000ff>public</font> AssociativeArray(<font color=#0000ff>int</font> length) {
pairs = <font color=#0000ff>new</font> Object[length][2];
}
<font color=#0000ff>public</font> <font color=#0000ff>void</font> put(Object key, Object value) {
<font color=#0000ff>if</font>(index >= pairs.length)
<font color=#0000ff>throw</font> <font color=#0000ff>new</font> ArrayIndexOutOfBoundsException();
pairs[index++] = <font color=#0000ff>new</font> Object[] { key, value };
}
<font color=#0000ff>public</font> Object get(Object key) {
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < index; i++)
<font color=#0000ff>if</font>(key.equals(pairs[i][0]))
<font color=#0000ff>return</font> pairs[i][1];
<font color=#0000ff>throw</font> <font color=#0000ff>new</font> RuntimeException(<font color=#004488>"Failed to find key"</font>);
}
<font color=#0000ff>public</font> String toString() {
String result = <font color=#004488>""</font>;
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < index; i++) {
result += pairs[i][0] + <font color=#004488>" : "</font> + pairs[i][1];
<font color=#0000ff>if</font>(i < index - 1) result += <font color=#004488>"\n"</font>;
}
<font color=#0000ff>return</font> result;
}
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
AssociativeArray map = <font color=#0000ff>new</font> AssociativeArray(6);
map.put(<font color=#004488>"sky"</font>, <font color=#004488>"blue"</font>);
map.put(<font color=#004488>"grass"</font>, <font color=#004488>"green"</font>);
map.put(<font color=#004488>"ocean"</font>, <font color=#004488>"dancing"</font>);
map.put(<font color=#004488>"tree"</font>, <font color=#004488>"tall"</font>);
map.put(<font color=#004488>"earth"</font>, <font color=#004488>"brown"</font>);
map.put(<font color=#004488>"sun"</font>, <font color=#004488>"warm"</font>);
<font color=#0000ff>try</font> {
map.put(<font color=#004488>"extra"</font>, <font color=#004488>"object"</font>); <font color=#009900>// Past the end</font>
} <font color=#0000ff>catch</font>(ArrayIndexOutOfBoundsException e) {
System.out.println(<font color=#004488>"Too many objects!"</font>);
}
System.out.println(map);
System.out.println(map.get(<font color=#004488>"ocean"</font>));
monitor.expect(<font color=#0000ff>new</font> String[] {
<font color=#004488>"Too many objects!"</font>,
<font color=#004488>"sky : blue"</font>,
<font color=#004488>"grass : green"</font>,
<font color=#004488>"ocean : dancing"</font>,
<font color=#004488>"tree : tall"</font>,
<font color=#004488>"earth : brown"</font>,
<font color=#004488>"sun : warm"</font>,
<font color=#004488>"dancing"</font>
});
}
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE><p><br></p>
<p>Your first observation might be that this appears to be a general-purpose tool, so why not put it in a package like <b>com.bruceeckel.tools</b>? Well, it is indeed a general-purpose tool—so useful, in fact, that <b>java.util</b> contains a number of associative arrays (which are also called <i>maps</i>) that do a lot more than this one does, and do it a lot faster. A large portion of Chapter 11 is devoted to associative arrays, but they are significantly more complicated, so using this one will keep things simple and at the same time begin to familiarize you with the value of associative arrays. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0484" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>In an associative array, the “indexer” is called a <i>key</i>, and the associated object is called a <i>value</i>. Here, we associate keys and values by putting them in an array of two-element arrays, which you see here as <b>pairs</b>. This will just be a fixed-length array that is created in the constructor, so we need <b>index</b> to make sure we don’t run off the end. When you <b>put( )</b> in a new key-value pair, a new two-element array is created and inserted at the next available location in <b>pairs</b>. If <b>index</b> is greater than or equal to the length of <b>pairs</b>, then an exception is thrown. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0485" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>To use the <b>get( )</b> method, you pass in the <b>key</b> that you want it to look up, and it produces the associated value as the result or throws an exception if it can’t be found. The <b>get( )</b> method is using what is possibly the least efficient approach imaginable to locate the value: starting at the top of the array and using <b>equals( )</b> to compare keys. But the point here is simplicity, not efficiency, and the real maps in Chapter 11 have solved the performance problems, so we don’t need to worry about it here. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0487" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>The essential methods in an associative array are <b>put( )</b> and <b>get( )</b>, but for easy display, <b>toString( )</b> has been overridden to print the key-value pairs. To show that it works, <b>main( )</b> loads an <b>AssociativeArray</b> with pairs of strings and prints the resulting map, followed by a <b>get( )</b> of one of the values. <font size="-2"><a href="mailto:TIJ3@MindView.net?Subject=[TIJ3]A0488" title="Send BackTalk Comment">Feedback</a></font><br></p>
<p>Now that all the tools are in place, we can use <b>instanceof</b> to count <b>Pet</b>s:<br></p>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: c10:PetCount.java</font>
<font color=#009900>// Using instanceof.</font>
<font color=#0000ff>package</font> c10;
<font color=#0000ff>import</font> com.bruceeckel.simpletest.*;
<font color=#0000ff>import</font> java.util.*;
<font color=#0000ff>public</font> <font color=#0000ff>class</font> PetCount {
<font color=#0000ff>private</font> <font color=#0000ff>static</font> Test monitor = <font color=#0000ff>new</font> Test();
<font color=#0000ff>private</font> <font color=#0000ff>static</font> Random rand = <font color=#0000ff>new</font> Random();
<font color=#0000ff>static</font> String[] typenames = {
<font color=#004488>"Pet"</font>, <font color=#004488>"Dog"</font>, <font color=#004488>"Pug"</font>, <font color=#004488>"Cat"</font>,
<font color=#004488>"Rodent"</font>, <font color=#004488>"Gerbil"</font>, <font color=#004488>"Hamster"</font>,
};
<font color=#009900>// Exceptions thrown to console:</font>
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
Object[] pets = <font color=#0000ff>new</font> Object[15];
<font color=#0000ff>try</font> {
Class[] petTypes = {
Class.forName(<font color=#004488>"c10.Dog"</font>),
Class.forName(<font color=#004488>"c10.Pug"</font>),
Class.forName(<font color=#004488>"c10.Cat"</font>),
Class.forName(<font color=#004488>"c10.Rodent"</font>),
Class.forName(<font color=#004488>"c10.Gerbil"</font>),
Class.forName(<font color=#004488>"c10.Hamster"</font>),
};
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < pets.length; i++)
pets[i] = petTypes[rand.nextInt(petTypes.length)]
.newInstance();
} <font color=#0000ff>catch</font>(InstantiationException e) {
System.out.println(<font color=#004488>"Cannot instantiate"</font>);
System.exit(1);
} <font color=#0000ff>catch</font>(IllegalAccessException e) {
System.out.println(<font color=#004488>"Cannot access"</font>);
System.exit(1);
} <font color=#0000ff>catch</font>(ClassNotFoundException e) {
System.out.println(<font color=#004488>"Cannot find class"</font>);
System.exit(1);
}
AssociativeArray map =
<font color=#0000ff>new</font> AssociativeArray(typenames.length);
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < typenames.length; i++)
map.put(typenames[i], <font color=#0000ff>new</font> Counter());
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < pets.length; i++) {
Object o = pets[i];
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Pet)
((Counter)map.get(<font color=#004488>"Pet"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Dog)
((Counter)map.get(<font color=#004488>"Dog"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Pug)
((Counter)map.get(<font color=#004488>"Pug"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Cat)
((Counter)map.get(<font color=#004488>"Cat"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Rodent)
((Counter)map.get(<font color=#004488>"Rodent"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Gerbil)
((Counter)map.get(<font color=#004488>"Gerbil"</font>)).i++;
<font color=#0000ff>if</font>(o <font color=#0000ff>instanceof</font> Hamster)
((Counter)map.get(<font color=#004488>"Hamster"</font>)).i++;
}
<font color=#009900>// List each individual pet:</font>
<font color=#0000ff>for</font>(<font color=#0000ff>int</font> i = 0; i < pets.length; i++)
System.out.println(pets[i].getClass());
<font color=#009900>// Show the counts:</font>
System.out.println(map);
monitor.expect(<font color=#0000ff>new</font> Object[] {
<font color=#0000ff>new</font> TestExpression(<font color=#004488>"%% class c10\\."</font>+
<font color=#004488>"(Dog|Pug|Cat|Rodent|Gerbil|Hamster)"</font>,
pets.length),
<font color=#0000ff>new</font> TestExpression(
<font color=#004488>"%% (Pet|Dog|Pug|Cat|Rodent|Gerbil|Hamster)"</font> +
<font color=#004488>" : \\d+"</font>, typenames.length)
});
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -