java编程思想---第十一章(持有对象)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java编程思想---第十一章(持有对象),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含8866字,纯文字阅读大概需要13分钟。
内容图文
![java编程思想---第十一章(持有对象)](/upload/InfoBanner/zyjiaocheng/844/06c721f13c82432f86a8478ff2df88d2.jpg)
含义:如果一个程序只包含固定数量的且生命期都是已经的对象,那么这就是一个非常简单的程序。
java对象通过引用来创建对象,开始的时候是数组作为保存一组对象的有效方式,但是数组是定长的,或者对象类型是复杂的,那么数据就不能满足要求了,因此
java容器:新增了,list,set,queue,和map,作为集合类,在collection类库下,每个容器都有特定的规范,且容器会自己调节大小,例如set 是无序不可重复的。map允许对象与对象之间关联起来。
11.1泛型和类型安全的容器
使用arraylist作为容器,使用size方法,判断有多少对象添加进来,
list.add()方法只能加入指定类型的元素,若元素未指定,强制加入(new的对象)时候,会有警告信息(obect类除外),可以使用@suppersswarnings注解来抑制警告。(一个类若没有显示的继承自那个类,那么它自动继承自object类)
11.2 java容器类库的用途是“保存对象”,并将其花费为两个不同的概念,
- collection
一个独立的元素序列,这些元素都服从一条或者多条规则,list必须按照插入顺序保存元素,set不能有重复元素, queuq按照队里确定顺序 - Map
一组成对的 “键值对” 对象,允许使用键来查找值。
示例: 使用Interger对象填充一个collection 并打印容器所有元素
public class SimpleCollection {
public static void main(String[] args) {
Collection<Integer> c = new ArrayList<Integer>();
for(int i = 0; i < 10; i++)
c.add(i); // Autoboxing
for(Integer i : c)
System.out.print(i + ", ");
}
} /* Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
*///:~
11.3 添加一组元素
Array.list() 接受一个数组或者一个使用逗号分隔的元素列表(使用可变参数)并将其转换为list对象,
Collection.addall()接受一个collection对象,数组或者逗号分隔的可变参数,讲元素添加到connection里,
public class AddingGroups {
public static void main(String[] args) {
Collection<Integer> collection =
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
Integer[] moreInts = { 6, 7, 8, 9, 10 };
collection.addAll(Arrays.asList(moreInts));
// Runs significantly faster, but you can't
// construct a Collection this way:
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 cannot be resized.
}
} ///:~
collection是一个接口,里面方法根据调用者在编译期间进行绑定它的子类
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object var1);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] var1);
boolean add(E var1);
boolean remove(Object var1);
boolean containsAll(Collection<?> var1);
boolean addAll(Collection<? extends E> var1);
boolean removeAll(Collection<?> var1);
11.4 容器的打印
容器的打印调用其自身(或者父类)的tostring方法, 或者调用Arrays.toString()来产生数组的打印方式。
public class PrintingContainers {
static Collection fill(Collection<String> collection) {
collection.add("rat");
collection.add("cat");
collection.add("dog");
collection.add("dog");
return collection;
}
static Map fill(Map<String,String> map) {
map.put("rat", "Fuzzy");
map.put("cat", "Rags");
map.put("dog", "Bosco");
map.put("dog", "Spot");
return map;
}
public static void main(String[] args) {
print(fill(new ArrayList<String>()));
print(fill(new LinkedList<String>()));
print(fill(new HashSet<String>()));
print(fill(new TreeSet<String>()));
print(fill(new LinkedHashSet<String>()));
print(fill(new HashMap<String,String>()));
print(fill(new TreeMap<String,String>()));
print(fill(new LinkedHashMap<String,String>()));
}
} /* Output:
[rat, cat, dog, dog]
[rat, cat, dog, dog]
[dog, cat, rat]
[cat, dog, rat]
[rat, cat, dog]
{dog=Spot, cat=Rags, rat=Fuzzy}
{cat=Rags, dog=Spot, rat=Fuzzy}
{rat=Fuzzy, cat=Rags, dog=Spot}
*///:~
以上展示了java容器类库中的两种主要类型,他们区别在于容器中每个槽位保存的元素个数,
- Collection在每个槽中只能保存一个元素,此类容器包括:
- list 特定的顺序保存一组元素,
- set 元素不能重复,
- queue 只允许在容器的一端插入对象,从另外一端移除对象,
- map 在每个槽内保存了两个对象,即键和与之相关联的值。
11.5 List
list接口在collection的基础上添加了大量的方法,使得可以在list的中间插入和移除元素
主要分为两种类型的List
基本类型ArrayList,它长于随机访问元素,插入和移除比较慢
LinkedList 在随机访问元素比较慢,但是优化了插入和删除元素。
exampl:主要介绍list的各个方法
public class LinkedListFeatures {
public static void main(String[] args) {
LinkedList<Pet> pets = new LinkedList<Pet>(Pets.arrayList(5));
print(pets);
// Identical:
print("pets.getFirst(): " + pets.getFirst());
print("pets.element(): " + pets.element());
// Only differs in empty-list behavior:
print("pets.peek(): " + pets.peek());
// Identical; remove and return the first element:
print("pets.remove(): " + pets.remove());
print("pets.removeFirst(): " + pets.removeFirst());
// Only differs in empty-list behavior:
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());
}
} /* Output:
[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
element :peek,poll remove 具体的参考jdk手册
11.6 迭代器
iterator只能单向移动,使用iterator方法适合,容器返回一个iterator,iterator将准备好返回序列的第一个元素。
使用next()获得序列中的下一个元素
使用hasnext()检查序列中是否还有元素
使用remove()将迭代器新近返回的元素删除。
11.7 linkedlist
getFirst()和element():返回第一个元素。list为空抛出异常
peek():返回第一个元素。list为空返回null
remove()和removeFirst():移除并返回列表的头。list为空抛出异常
poll():移除并返回列表的头。list为空返回null
addFirst()、add()、offer()、addLast():将某个元素插入到头(尾)部。
11.8Stack
栈通常指后进先出的容器。
pop():返回并移除栈顶元素。
peek():返回栈顶元素,不移除。
11.9 Set
Set不保存重复元素。
HashSet使用了散列函数,TreeSet使用红-黑树结构。
11.10Map
containsKey(key):查找是否包含某个键
containsValue(value):查找是否包含某个值。
11.11 Queuq
队列是典型的先进先出容器。因为它可以安全地将对象从一个任务传输给另一个任务。
offer():在允许的情况下,将元素插入到队尾,或者返回false。
peek()和element():在不移除情况下返回队头。
remove()和poll():移除并返回队头。
11.12 Collectionhe Iterator
collection是描述所有序列容器的共性根接口,
public class InterfaceVsIterator {
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();
}
public static void main(String[] args) {
List<Pet> petList = Pets.arrayList(8);
Set<Pet> petSet = new HashSet<Pet>(petList);
Map<String,Pet> petMap =
new LinkedHashMap<String,Pet>();
String[] names = ("Ralph, Eric, Robin, Lacey, " +
"Britney, Sam, Spot, Fluffy").split(", ");
for(int i = 0; i < names.length; i++)
petMap.put(names[i], petList.get(i));
display(petList);
display(petSet);
display(petList.iterator());
display(petSet.iterator());
System.out.println(petMap);
System.out.println(petMap.keySet());
display(petMap.values());
display(petMap.values().iterator());
}
} /* Output:
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
4:Pug 6:Pug 3:Mutt 1:Manx 5:Cymric 7:Manx 2:Cymric 0:Rat
{Ralph=Rat, Eric=Manx, Robin=Cymric, Lacey=Mutt, Britney=Pug, Sam=Cymric, Spot=Pug, Fluffy=Manx}
[Ralph, Eric, Robin, Lacey, Britney, Sam, Spot, Fluffy]
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx
11.13 foreach与迭代器
public class ForEachCollections {
public static void main(String[] args) {
Collection<String> cs = new LinkedList<String>();
Collections.addAll(cs,
"Take the long way home".split(" "));
for(String s : cs)
System.out.print("'" + s + "' ");
}
} /* Output:
'Take' 'the' 'long' 'way' 'home'
*///:~
foreach可以使用与任何collection对象。在javase5 之后引入了Iterable接口,该接口包含一个能够产生iterator()的方法,并且iterable接口被foreach用来序列中移动.
11.14 总结
Java提供了大量持有对象的方式:
数组将数字与对象联系起来。
Collection保存单一的元素,而Map保存相关联的键值对。
List也建立数字索引与对象的关联。
如果要进行大量随机访问,就使用ArrayList,如果经常从中间插入或删除元素,则应该使用LinkedList。
各种Queue以及栈行为,由LinkedList支持。
Map是一种将对象与对象相关联的设计。HashMap用来快速访问,TreeMap保持“键”始终处于排序状态。
Set不接受重复元素。HashSet提供最快查询速度,TreeSet保持元素处于排序状态。LinkedSet以插入顺序保存元素。
新程序中不应使用过时的Vector,HashTable和Stack
内容总结
以上是互联网集市为您收集整理的java编程思想---第十一章(持有对象)全部内容,希望文章能够帮你解决java编程思想---第十一章(持有对象)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。