print("pets.poll(): " + pets.poll());
print(pets);
pets.addFirst(new Rat());
print("After addFirst(): " + pets);
pets.offer(Pets.randomPet());
print("After offer(): " + pets);
pets.add(Pets.randomPet());
print("After add(): " + pets);
pets.addLast(new Hamster());
print("After addLast(): " + pets);
print("pets.removeLast(): " + pets.removeLast());
}
}
运行结果:
[Rat, Manx, Cymric, Mutt, Pug]
pets.getFirst(): Rat
pets.element(): Rat
pets.peek(): Rat
pets.remove(): Rat
pets.removeFirst(): Manx
pets.poll(): Cymric
[Mutt, Pug]
After addFirst(): [Rat, Mutt, Pug]
After offer(): [Rat, Mutt, Pug, Cymric]
After add(): [Rat, Mutt, Pug, Cymric, Pug]
After addLast(): [Rat, Mutt, Pug, Cymric, Pug, Hamster]
pets.removeLast(): Hamster
JAVA容器小结(3)
时间:2010-01-06
List的排序和查询:List排序和查询所使用的方法与对象数组所使用的相应方法有相同的名字和语法,只是用Collections的static方法代替Arrays的方法而已。例子如下:
/**//*
* @(#)ListSortSearch.java 1.0 May 18, 2008
* @author:Administrator
* Copyright 2008 CSS WEB Microsystems, Inc. All rights reserved.
* CSS WEB ROOM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package containers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import containers.Utilities;
import static net.mindview.util.Print.*;
public class ListSortSearch ...{
public static void main(String[] args) ...{
List<String> list = new ArrayList<String>(Utilities.list);
list.addAll(Utilities.list);
print(list);
Collections.shuffle(list,new Random(47));
print("shuffled: " + list);
ListIterator<String> it = list.listIterator(10);
while(it.hasNext()) ...{
it.next();
it.remove();
}
print("Trimmed: " + list);
Collections.sort(list);
print("sorted: " + list);
String key = list.get(7);
int index = Collections.binarySearch(list, key);
print("Location of " + key + " is " + index +
", list.get(" + index + ") = " + list.get(index));
Collections.sort(list,String.CASE_INSENSITIVE_ORDER);
print("Case-insensitive sorted: " + list);
key = list.get(7);
index = Collections.binarySearch(list, key, String.CASE_INSENSITIVE_ORDER);
print("Location of " + key + " is " + index +
", list.get(" + index + ") = " + list.get(index));
}
}
|