ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaApi学习---ArrayList类

2022-05-16 00:33:13  阅读:186  来源: 互联网

标签:index int ArrayList elementData --- Person JavaApi public size


ArrayList类常用方法

继承体系结构图

构造方法

public ArrayList()  //默认Capacity=10

public ArrayList(int initialCapacity) //提供初始容量  提供的范围在0~Integer.MAX_VALUE = 2147483647 之间

public ArrayList(Collection<? extends E> c)  //提供一个集合
    

    ArrayList<Integer> arr1 = new ArrayList<>();

    ArrayList<Integer> arr2 = new ArrayList<>(20);

    List<Integer> list = new ArrayList<>();
    ArrayList<Integer> arr3 = new ArrayList<>(list);

扩容:每次扩容为原容量的1.5倍

add()添加一个元素

//在最后添加一个元素  
public boolean add(E e) {
    ensureCapacityInternal(size + 1);   //每次添加前会判断是否需要扩容
    elementData[size++] = e;
    return true;
}

//在指定位置添加元素
public void add(int index, E element) {
    //检查index是否超过数组的长度
    rangeCheckForAdd(index); 

    ensureCapacityInternal(size + 1);  
    //将数组从index位置往后移动
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
 }

addAll()添加集合中的全部元素

public boolean addAll(Collection<? extends E> c)   //在方法里面调用循环调用add(e)方法

    
public boolean addAll(int index, Collection<? extends E> c) //在方法里面调用循环调用add(index,e)方法

get(int index)返回index位置的元素

//index需要在list.size()之间否则就会报:IndexOutOfBoundsException
    
System.out.println(arr1.get(2)); //3
System.out.println(arr1.get(5)); //IndexOutOfBoundsException

clear()清除所有元素

ArrayList<Integer> arr1 = new ArrayList<>();

arr1.add(1);
System.out.println(arr1.toString()); // [1]
arr1.clear();
System.out.println(arr1.toString()); //[]

clone()返回数组的克隆对象(浅克隆)

ArrayList<Integer> arr1 = new ArrayList<>();

arr1.addAll(Arrays.asList(1, 2, 3, 4));

ArrayList<Integer> arrayList = (ArrayList<Integer>) arr1.clone();

System.out.println(arr1);  //[1, 2, 3, 4]
System.out.println(arrayList); //[1, 2, 3, 4]

contains(e) 集合是否包含此元素,包含返回true,否则返回False

        ArrayList<Integer> arr1 = new ArrayList<>();

        arr1.addAll(Arrays.asList(1, 2, 3, 4));

        System.out.println(arr1.contains(1)); //true

ensureCapacity(int minCapacity)改变该集合的容量大小

forEach(Consumer<? super E> action) 对集合中的元素进行遍历,可以对每个元素进行操作

//对集合中每个元素扩大10倍后输出
  arr1.forEach(i ->{
       System.out.printf("%d、", i * 10); //10、20、30、40、
   });

indexOf(object o)

//返回元素第一出现的下标,如果该元素不在集合中就会返回-1
  public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++) //从前往后找
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))   //对象需要重写equals方法
                    return i;
        }
        return -1;
    }

//Person类没有重写equals方法时,
       ArrayList<Person> peoples = new ArrayList<>();

        peoples.add(new Person("张三",18));
        peoples.add(new Person("李四",19));
        peoples.add(new Person("王五",20));

        System.out.println(peoples.indexOf(new Person("张三", 18))); // -1

//Person类重写equals方法后。
	 System.out.println(peoples.indexOf(new Person("张三", 18))); // 0

//Person类

public class Person {

    private String name;
    private Integer age;

    public Person(){}
    public Person(String name, Integer age){
        this.name=name;
        this.age = age;
    }

    public void say(){
        System.out.println("I can talk");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(name, person.name) && Objects.equals(age, person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

lastIndexOf(Object o)

//返回元素最后一次出现的下标,如果该元素不在集合中就会返回-1
//与indexOf相反,

    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--) //从后往前找
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

isEmpty()判断集合是否为空

  //集合中没有元素就返回true否则返回false
public boolean isEmpty() {
        return size == 0;
    }

iterator()获取集合的迭代器

Iterator<Person> iterator = peoples.iterator();

while (iterator.hasNext()){
    Person person = iterator.next();
    System.out.println(person.toString());
}

//        Person{name='张三', age=18}
//        Person{name='李四', age=19}
//        Person{name='王五', age=20}

listIterator()

//listIterator() 默认是从下标0开始的
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

//listIterator(int index) 可以指定下标
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)   //指定的范围必须在0~~size之间
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }


    ListIterator<Person> iterator = peoples.listIterator(3);

    while (iterator.hasPrevious()){   //从后往前迭代
        Person person = iterator.previous();
        System.out.println(person.toString());
	}
iterator()和listIterator()的区别
iterator:
	不仅可以对list进行迭代,还可以对set进行迭代
    只能单向的迭代,从前往后
listIterator:
     只能对list进行迭代。
     可以双向迭代,既可从前往后,也可从后往前进行迭代

remove(int index)移除集合指定位置的元素,并返回index位置的元素

//如果移除的不是最后一个元素,将会造成集合的拷贝,(所以删除性能也是挺慢的)    
//remove(int index)
public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)		//如果不是最后一个元素,将会带来数据的拷贝
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; 

        return oldValue;
    }


// remove(Object o)移除第一次出现的元素
    public boolean remove(Object o) {
        if (o == null) { //即使传进来一个null值,只要集合中存在null值,也会被删除
            for (int index = 0; index < size; index++) //因为从前往后遍历,将会删除第一出现的元素
                if (elementData[index] == null) {
                    fastRemove(index); 
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

removeAll(Collection<?> c)

//移除和集合c中相同的元素
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);  // 判断集合c 是否为null
        return batchRemove(c, false);
    }

//主要是下面的移除方法
private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement) // 如果集合c中不存源集合的元素,
                    elementData[w++] = elementData[r]; //就将这个元素放到源集合中,从前往后放
        } finally {
            // Preserve behavioral compatibility with AbstractCollection, 兼容AbstractCollection
            // even if c.contains() throws.  // 就算 c.contains()抛出异常,导致没有遍历完
            if (r != size) { // 如果没有遍历完,就将r后面的元素全部复制到源集合中,从w的位置
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {  // 如果w不等于size 说明有源集合中有c集合相同的元素,就把w后面的元素全部删除,也就实现了功能
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

removeIf(Predicate<? super E> filter)

//从集合中移除符合条件的元素
//传个断言型的参数

    public boolean removeIf(Predicate<? super E> filter) {
		....
            
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {  //处理符合条件的元素
                removeSet.set(i);  //将符合条件的元素放到处理的set中
                removeCount++;
            }
        }
        ...
		//将要移除的元素在这里移除
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }


    //移除年龄小于20岁的
    peoples.removeIf(p -> p.getAge() < 20);

    System.out.println(peoples.toString()); //[Person{name='王五', age=20}]

removeRange(int fromIndex, int toIndex)

//移除指定范围之间的元素
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

replaceAll(UnaryOperator operator)

//将集合中的元素,通过operator的操作后,将经过加工的元素替换原来的元素

     peoples.replaceAll(p->"张三".equals(p.getName()) ? new Person() : p);
     System.out.println(peoples); //[Person{name='null', age=null}, Person{name='李四', age=19}, 						                        Person{name='王五', age=20}]

retainAll(Collection<?> c)

//和removeAll是相对的,保存集合c中相同的元素
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

set(int index, E element)

 //将index位置的元素用传进来的替换,并返回原元素 
public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

size()返回集合中的个数

sort(Comparator<? super E> c)

//用一定的规则将集合中的元素进行排序

    peoples.sort(new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.getAge()- o2.getAge();
        }
    });
    System.out.println(peoples);
    //[Person{name='张三', age=18}, Person{name='李四', age=19}, Person{name='王五', age=20}]

subList(int fromIndex, int toIndex)

//返回源集合中fromIndex--toIndex之间的所有元素

toArray()

//源集合转为数组形式
   public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

 Person[] persons = (Person[]) peoples.toArray();

//重构方法,将源集合,转化为 a类型的数组

public <T> T[] toArray(T[] a) {
     if (a.length < size)
         // Make a new array of a's runtime type, but my contents:
         return (T[]) Arrays.copyOf(elementData, size, a.getClass()); 
     System.arraycopy(elementData, 0, a, 0, size);
     if (a.length > size)
         a[size] = null;
     return a;
 }

trimToSize()

//将集合容量缩小为当前集合的实际容量,如果size为0,那还是默认的容量。
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

标签:index,int,ArrayList,elementData,---,Person,JavaApi,public,size
来源: https://www.cnblogs.com/hxf-zb/p/16275389.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有