Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement own ArrayList<> without using collections

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:

  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

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

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

    }
}
like image 453
C graphics Avatar asked Oct 01 '22 04:10

C graphics


1 Answers

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

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 false and when returns true?

See the javadoc

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

It always returns true.

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

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

java ArrayList source code

like image 127
Sotirios Delimanolis Avatar answered Oct 13 '22 12:10

Sotirios Delimanolis