Java 在不使用集合的情况下实现自己的 ArrayList<>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22752206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:41:37  来源:igfitidea点击:

Implement own ArrayList<> without using collections

javacollectionsarraylist

提问by C graphics

I am trying to implement my own ArrayList without using java collections for practice purposes. At this stage I want to implement two of main methods, add(E) and get(int) tp get the idea. My code is given below. However I encountered few issues:

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

  1. The line "return (E) myData[index]" issues warning "Type safety: Unchecked cast from Object to E". How can I address that
  2. 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?
  3. Where can I find the source code of java 7 implementation of ArrayList
  1. “return (E) myData[index]”行发出警告“类型安全:从对象到 E 的未经检查的强制转换”。我该如何解决
  2. ArrayList.add(T) 的 Java 7 实现返回一个布尔值。在什么情况下 add() 必须返回 false。在什么逻辑下它返回false,什么时候返回true?
  3. 哪里可以找到ArrayList的java 7实现的源代码

PS. Kindly don't just answer question 3 and refer me to the sucrose code for one and two!

附注。请不要只回答问题 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

    }
}

回答by Sotirios Delimanolis

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

“return (E) myData[index]”行发出警告“类型安全:从对象到 E 的未经检查的强制转换”。我该如何解决

Suppress the warning

取消警告

@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 falseand when returns true?

Java 7 实现ArrayList.add(T)返回一个boolean. 在什么情况下add()必须返回false。它在什么逻辑下返回false以及何时返回true

See the javadoc

请参阅javadoc

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

返回:( true由 指定Collection.add(E)

It always returns true.

它总是返回true

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

哪里可以找到ArrayList的java 7实现的源代码

In your JDK installation's src.ziparchive or find it online by simply searching

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

java ArrayList source code

java ArrayList 源代码

回答by tambykojak

  1. I do not think you could avoid that Type safety warning using a generic type. If it is really bothering you, you could add @SupressWarnings("unchecked").
  2. Hmmm, I'm not sure about this one, but the Android implementation of Java, which isn't exactly the same says that it "always returns true". This is weird to me, but here's the link: http://developer.android.com/reference/java/util/ArrayList.html#add(E).
  3. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java, but definitely download the source and check it out.
  1. 我认为您不能使用泛型类型来避免该类型安全警告。如果它真的困扰你,你可以添加@SupressWarnings("unchecked").
  2. 嗯,我不确定这个,但 Java 的 Android 实现并不完全相同,它说它“总是返回 true”。这对我来说很奇怪,但这是链接:http: //developer.android.com/reference/java/util/ArrayList.html#add(E)
  3. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java,但一定要下载源代码并检查出来。

回答by Makoto

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

“return (E) myData[index]”行发出警告“类型安全:从对象到 E 的未经检查的强制转换”。我该如何解决?

You're always going to have this unchecked cast warning, since you're working with a generic array. Generics and arrays don't really mixall that well, but the better convention is to have the generic type attached to the array anyway:

由于您使用的是通用数组,因此您总是会收到这种未经检查的强制转换警告。泛型和数组并没有真正混合得那么好,但更好的约定是无论如何都将泛型类型附加到数组:

private E[] myData = (E[]) new Object[DEFAULT_SIZE];

You could always add @SuppressWarnings("unchecked")to the field itself to get that warning to go away.

您始终可以添加@SuppressWarnings("unchecked")到字段本身以消除该警告。

@SuppressWarnings("unchecked")
private E[] myData = (E[]) new Object[DEFAULT_SIZE];

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?

ArrayList.add(T) 的 Java 7 实现返回一个布尔值。在什么情况下 add() 必须返回 false。在什么逻辑下它返回false,什么时候返回true?

This is a bit of an interesting question. Typically, one would expect that the restrictions on addcome from Collections#add:

这是一个有点有趣的问题。通常,人们会期望限制add来自Collections#add

Collections that support this operation may place limitations on what elements may be added to this collection. In particular, some collections will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.

支持此操作的集合可能会对可以添加到此集合中的元素设置限制。特别是,一些集合会拒绝添加空元素,而另一些集合会对可能添加的元素类型施加限制。集合类应在其文档中明确指定对可以添加哪些元素的任何限制。

...but, since ArrayListis special in that it's designed to always expand its space when it's about to run out, it will (in theory) alwaysbe able to add something in. So, it should alwaysreturn true.

...但是,由于ArrayList它的特殊之处在于它旨在在即将用完时始终扩展其空间,因此(理论上)它始终能够添加一些东西。因此,它应该始终返回true

Where can I find the source code of Java 7 implementation of ArrayList?

我在哪里可以找到 ArrayList 的 Java 7 实现的源代码?

Grepcodeis usually a good resource. You could also find it in src.zip if you downloaded the JDK with sources.

Grepcode通常是一个很好的资源。如果你下载了带有源代码的 JDK,你也可以在 src.zip 中找到它。

回答by Uddhav Gautam

I have done little explanation in comments because it is clear to understand.

我在评论中做了很少的解释,因为很清楚理解。

public class MyArrayList<E extends Object> {

    private static int initialCapacity = 5;
    private static int currentSize;
    private Object[] myArrayList = {}, temp = {};

    private static int currentIndex = 0;

    public static void main(String[] args) {
        MyArrayList arrList = new MyArrayList();
        arrList.add("123"); //add String
        arrList.printAllElements();
        arrList.add(new Integer(111)); //add Integer
        arrList.printAllElements();

        arrList.add(new Float("34.56")); //add Integer
        arrList.printAllElements();

        arrList.delete("123");
        arrList.printAllElements();

        arrList.delete(123);
        arrList.printAllElements();
        arrList.delete(123);

        arrList.printAllElements();

    }

    public MyArrayList() {  //creates default sized Array of Objects
        myArrayList = new Object[initialCapacity]; //generic expression

        /* everytime I cross my capacity, 
    I make double size of Object Array, copy all the elements from past myObject Array Object
         */
    }

    public MyArrayList(int size) { //creates custom sized Array of Objects
        myArrayList = new Object[size];
    }

    public void add(Object anyObj) {
        //add element directy
        myArrayList[currentIndex] = anyObj;
        currentSize = myArrayList.length;
        currentIndex++;
        if (currentIndex == currentSize) {
            createDoubleSizedObjectArray(currentSize);
        }
    }

    //print all elements
    public void printAllElements() {
        System.out.println("Displaying list : ");
        for (int i = 0; i < currentIndex; i++) {
            System.out.println(myArrayList[i].toString()); 
        }
    }

    private void createDoubleSizedObjectArray(int currentSize) {
        temp = myArrayList.clone();
        myArrayList = new MyArrayList[2 * currentSize];  //myObject pointer big size data structure

//         myObject = temp.clone(); //probably I can do this here as well. Need to check this
        System.arraycopy(temp, 0, myArrayList, 0, currentSize);

    }

    void delete(Object object) {
        //if already empty 
        if (currentIndex == 0) {
            System.out.println("Already empty!");
            return;
        }
        //you don't need to delete anything. I can simply override the storage
        currentIndex--;
    }
}