5

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

    }
}
Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
C graphics
  • 6,750
  • 18
  • 75
  • 124
  • If you download the [JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) you can find the source code at $JDK_HOME/src.zip. If you don't have the JDK, you can use websites like http://grepcode.com/. – Jeffrey Mar 31 '14 at 01:22
  • Are you *implementing* List? – aliteralmind Mar 31 '14 at 01:24
  • http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/ArrayList.java?av=f – jmj Mar 31 '14 at 01:26
  • inconsistent style (spaces around `=` and other binary operations) – Display Name Mar 31 '14 at 01:30

4 Answers4

3

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

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
2

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

You're always going to have this unchecked cast warning, since you're working with a generic array. Generics and arrays don't really mix all 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")
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?

This is a bit of an interesting question. Typically, one would expect that the restrictions on add come from 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 ArrayList is special in that it's designed to always expand its space when it's about to run out, it will (in theory) always be able to add something in. So, it should always return true.

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

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

Community
  • 1
  • 1
Makoto
  • 96,408
  • 24
  • 164
  • 210
0
  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.
tambykojak
  • 2,029
  • 1
  • 11
  • 25
-1

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--;
    }
}
Uddhav Gautam
  • 6,052
  • 3
  • 39
  • 54