Java中几种列表的简单介绍

java中列表的简单介绍与迭代器

Collection类中有多种容器类型:

  1. List 以特定的顺序保存元素
  2. Set 元素不能重复
  3. Queue 链表,只能从一端插入对象,从另一端取出 遵循先进先出原则
  4. Map 键值对插入

List中有两种类型的列表:

  • ArrayList:随机访问快,插入删除慢
  • LinkedList:插入删除快,但是随机访问慢。还添加了作为栈、队列、双端列表的方法,可以直接作为栈来使用,遵守“后进先出,先进后出”的原则,其中有几个常用方法:
    romove() romovefirst()返回列表头部并移除
    addfirst() add() addlast()插入到列表的尾部
    getfirst() element() peek()返回列表的头部

Set
Set具有与Collection完全一样的接口,因此没有额外的功能只是行为不同,不能保存重复的元素

  • HashSet 使用散列
  • TreeSet 将元素存储在红-黑树数据结构之中
  • LinkedHashSet 也使用了散列,但使用了链表来维护元素的插入顺序
    contains(元素)检查是否包含该元素
    三种列表都具有不同的元素存储方式

Map
采用键值对Key-Value的形式存储对象
- HashMap:是无序的,与放入的顺序无关
- LinkedHashMap:存入时会记录put的毫米数,遍历时按照存入的顺序输出

Map<K,V> map=new HashMap<K,V>();
map.put(k,v);
map.get(k)返回value

Map也可以扩展到多维

Map<K,List<?>> maps=new HashMap<K,List<?>>();

2在链表中添加元素的几个方法

1 Collections.addAll()接受多个参数,将之后的参数转化为数组存入第一个参数的序列中

2 在创建列表实例时,传入参数
可以使用Array.asList()将参数数组转化为列表list的形式,参数可以为数组或者逗号分割的元素列表

Collection<> collection=new ArrayList<>(Arrays.asList(1,2,3,4,5))//直接传入参数
Collections.addAll(collection,1,2,3,4,5,6)//参数转化为数组存入第一个参数的序列中
Collection.addAll(collection,moreInts)

3 foreach与迭代器Iterable

由于所有的Collection类型的对象都被强制要求implements Iterable 接口,故任何Collection对象都要能返回一个能遍历其的迭代器Iterator。

Collection<> collection=new ArrayList<>
Iterator<> it=collection.iterator()

迭代器的内部代码如下

Interface Iterator<E>{
boolean  hasNext() 
          Returns true if the iteration has more elements.

 E  next() 
          Returns the next element in the iteration.

void  remove() 
          Removes from the underlying collection the last element returned by the iterator (optional operation).
          }

iterator使用时通常都包含着这三个方法

Iteraotr it= arrayList.Iterator();
while(it.hasNext())
{
  print(it.next());
      it.remove();
}

foreach遍历,内部就使用了Iterable接口的iterater方法:

for(type var:coll()){body-of-loop; }
就等价于:
for(Iterator<type> iter=coll.iterator(); iter.hasNext();){
    type var=iter.next();
    body-of-loop;
}

所以所有实现了Iterable的类,都可以将他用于foreach语句中,比方说:

public class IterableClass implements Iterable<String>{
    protected String[] words=("And that is how "+
    "we know the earth to be banana-shaped.").split(" ")//以空格分割为数组的形式
    public Iterable<String> iterator(){
        return new Iterable<String>(){
            private int index=0;
            public boolean hasNext(){
                return index<words.length();
            }
            public String next(){
                return word[index++];
            }
            public remove(){}
        };
    }
    public static void main(String[] args){
        for(String s:new IterableClass())
            System.out.print(s+" ")
    }
}
Output: And that is how we know the earth to be banana-shaped.
  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值