java - 不使用集合实现自己的 ArrayList<>

标签 java collections arraylist

出于练习目的,我正在尝试在不使用 java 集合的情况下实现我自己的 ArrayList。在这个阶段我想实现两个主要方法,add(E) 和 get(int) tp 明白了。我的代码如下。但是我遇到了一些问题:

  1. “return (E) myData[index]”行发出警告“类型安全:未检查的从对象到 E 的转换”。我该如何解决这个问题
  2. ArrayList.add(T) 的 Java 7 实现,返回一个 boolean 值。在什么情况下 add() 必须返回 false。它在什么逻辑下返回 false,什么时候返回 true?
  3. 哪里可以找到java 7实现ArrayList的源码

附言。请不要只回答问题 3 并向我推荐一和二的蔗糖代码!

import java.util.Arrays;

public class MyArrayList<E>{
    private final int DEFAULT_SIZE=2;
    private Object[] myData = new Object[DEFAULT_SIZE];
    private int actSize=0;

    public boolean add(E data){
        if (actSize>=myData.length/2){
            increaseSize();
        }
        myData[actSize++] = data;
        return true;//when can it be false?
    }

    private void increaseSize()throws RuntimeException{
        myData = Arrays.copyOf(myData, myData.length*2);
    }

    public E get(int index) throws RuntimeException{
        if (index >= actSize){
            throw new IndexOutOfBoundsException(); 
        }
        return (E) myData[index];
    }

    public static void main(String[] args) {
        MyArrayList<String> arList = new MyArrayList<>();
        arList.add("Hello");
        arList.add("Bye bye!");
        System.out.println(arList.get(1));// prints Bye bye! which is correct

    }
}

最佳答案

The line "return (E) myData[index]" issues warning "Type safety: Unchecked cast from Object to E". How can I address that

抑制警告

@SuppressWarnings("unchecked")

The Java 7 implementation of ArrayList.add(T) returns a boolean. Under what circumstances the add() has to return false. Under what logic it return false and when returns true?

参见 javadoc

Returns: true (as specified by Collection.add(E))

它总是返回 true

Where can I find the source code of java 7 implementation of ArrayList

在您的 JDK 安装的 src.zip 存档中或通过简单搜索在线找到它

java ArrayList source code

关于java - 不使用集合实现自己的 ArrayList<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752206/

相关文章:

java - 为什么不同类型的空集合相等?

java - 如何在Java中的类对象数组中查找非唯一元素

java - 将通用列表转换为非通用列表有什么影响?

java - 编码Bat xyz那里

java - 为什么当我删除 toLowerCase() 时却不对我的单词进行排序?

java - 希望使用 Java 创建随机数组

java - 如何随机化输出

java - 更改隔离级别 - hibernate.connection.isolation 不起作用

java - 确定要使用的 Java 集合类型

c# - 为什么使用 'ICollection<T>' ?