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:
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
}
}
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 aboolean
. Under what circumstances theadd()
has to returnfalse
. Under what logic it returnfalse
and when returnstrue
?
See the javadoc
Returns:
true
(as specified byCollection.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With